@httpc/kit
Version:
httpc toolbox for building function-based API with minimal code and end-to-end type safety
94 lines (93 loc) • 4.11 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import assert from "assert";
import { injectable } from "tsyringe";
import { fetch } from "../fetch";
import { BaseService } from "../services";
import { options } from "../di";
import { logger } from "../logging";
import { cleanUndefined } from "../utils";
const MAILERSEND_API = "https://api.mailersend.com/v1";
let MailersendEmailSender = class MailersendEmailSender extends BaseService() {
constructor(logger, options) {
//@ts-expect-error
super(...arguments);
this.options = options;
}
async send(params) {
assert(!!(params.bodyHtml || params.bodyText), "one of bodyHtml and bodyText is required");
if (Array.isArray(params.to)) {
assert(params.to.length > 0, "options.to must have at least an item");
}
const to = mapEmailRecipient(params.to);
const from = params.from ? mapEmailRecipient(params.from)[0] :
this.options.defaultSender ? mapEmailRecipient(this.options.defaultSender) :
undefined;
const request = cleanUndefined({
to,
from,
html: params.bodyHtml,
text: params.bodyText,
subject: params.subject,
cc: params.cc ? mapEmailRecipient(params.cc) : undefined,
bcc: params.bcc ? mapEmailRecipient(params.bcc) : undefined,
});
if (this.logger.isLevelEnabled("debug")) {
this.logger.debug("Email params: %o", { ...request, bodyHtml: "<omitted>", bodyText: "<omitted>" });
}
await this._sendMail(request);
this.logger.verbose("Email sent(%s)", to[0].email);
}
async _sendMail(params) {
assert(this.options.apiKey, "ApiKey must be set");
try {
const token = this.options.apiKey;
const response = await fetch(`${MAILERSEND_API}/email`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
},
body: JSON.stringify(params)
});
if (response.status >= 400) {
throw response;
}
}
catch (ex) {
const error = ex instanceof Error ? ex : undefined;
const response = ex instanceof Error ? undefined : ex;
const body = response ? await response.json().catch(() => null) : undefined;
this._raiseError("processing_error", "Email send failed", {
errorMessage: error && `[${error.name}] ${error.message}`,
httpStatus: response?.status,
httpResponse: body
});
}
}
};
MailersendEmailSender = __decorate([
injectable(),
__param(0, logger()),
__param(1, options()),
__metadata("design:paramtypes", [Object, Object])
], MailersendEmailSender);
export { MailersendEmailSender };
function mapEmailRecipient(r) {
if (!Array.isArray(r)) {
return mapEmailRecipient([r]);
}
return r.map(x => (typeof x === "string" ?
{ email: x } :
x));
}