UNPKG

@explita/cloud-mail-client

Version:

A simple mail client for Node applications.

46 lines (45 loc) 1.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.httpClient = httpClient; const error_1 = require("./error"); async function httpClient(apiPath, options) { if (!process.env.ECP_MAIL_TOKEN) { throw new Error("Missing ECP_MAIL_TOKEN environment variable. Please set it in your .env file."); } let [apiUrl, apiKey] = atob(process.env.ECP_MAIL_TOKEN).split("$"); if (!apiUrl || !apiKey) { throw new Error("Invalid API URL or API key, please set ECP_MAIL_TOKEN in your .env file."); } const { method = "POST", body, headers, ...rest } = options !== null && options !== void 0 ? options : {}; const res = await fetch(`${apiUrl}${apiPath}`, { method, body: body ? JSON.stringify(body) : undefined, headers: { "Content-Type": "application/json", "x-api-key": apiKey, "x-server-to-server": "true", }, ...rest, }); if (!res.ok) { let errorData = { message: "Something went wrong." }; try { errorData = await res.json(); } catch { // response is not JSON, keep default errorData } const baseMessage = errorData.message || "Unexpected error occurred."; if (res.status === 401) { throw new error_1.MailError("Unauthorized: Please check the token or login again.", errorData, 401); } if (res.status === 403) { throw new error_1.MailError("Forbidden: You don't have permission to access this resource.", errorData, 403); } if (res.status === 404) { throw new error_1.MailError("Not Found: The requested API path was not found.", errorData, 404); } throw new error_1.MailError(baseMessage, errorData, res.status); } return (await res.json()); }