60 lines
1.9 KiB
JavaScript
60 lines
1.9 KiB
JavaScript
// server/postal.ts
|
|
function createPostalClient(options) {
|
|
const baseUrl = options.baseUrl.trim();
|
|
const apiKey = options.apiKey.trim();
|
|
const from = options.from.trim();
|
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
const enabled = baseUrl.length > 0 && apiKey.length > 0 && from.length > 0;
|
|
return {
|
|
enabled,
|
|
async sendMessage(input) {
|
|
if (!enabled || input.to.length === 0) {
|
|
return;
|
|
}
|
|
const endpoint = new URL("/api/v1/send/message", ensureTrailingSlash(baseUrl));
|
|
const response = await fetchImpl(endpoint, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"X-Server-API-Key": apiKey
|
|
},
|
|
body: JSON.stringify({
|
|
from,
|
|
to: input.to,
|
|
subject: input.subject,
|
|
plain_body: input.plainBody,
|
|
html_body: input.htmlBody
|
|
})
|
|
});
|
|
const rawBody = await response.text().catch(() => "");
|
|
const payload = rawBody.length > 0 ? (() => {
|
|
try {
|
|
return JSON.parse(rawBody);
|
|
} catch {
|
|
return null;
|
|
}
|
|
})() ?? null : null;
|
|
if (!response.ok || payload?.status !== "success") {
|
|
const details = payload?.error?.trim() || payload?.message?.trim() || rawBody.trim().slice(0, 500) || "no_response_body";
|
|
throw new Error(`postal_send_failed:${response.status}:${details}`);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
function createPostalClientFromEnv(options = {}) {
|
|
const env = options.env ?? process.env;
|
|
return createPostalClient({
|
|
baseUrl: env[options.baseUrlEnv ?? "POSTAL_URL"] ?? "",
|
|
apiKey: env[options.apiKeyEnv ?? "POSTAL_API_KEY"] ?? "",
|
|
from: env[options.fromEnv ?? "POSTAL_MESSAGE_FROM"] ?? "",
|
|
fetchImpl: options.fetchImpl
|
|
});
|
|
}
|
|
function ensureTrailingSlash(value) {
|
|
return value.endsWith("/") ? value : `${value}/`;
|
|
}
|
|
export {
|
|
createPostalClient,
|
|
createPostalClientFromEnv
|
|
};
|
|
//# sourceMappingURL=index.js.map
|