@moreapp/common-nodejs 0.13.1 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ export interface Recipient {
2
+ email: string;
3
+ name?: string;
4
+ type: "to" | "cc" | "bcc";
5
+ }
6
+ export interface Attachment {
7
+ name: string;
8
+ type: string;
9
+ data: string;
10
+ inline: boolean;
11
+ }
12
+ type MailSendResponse = {
13
+ id: string;
14
+ };
15
+ export declare class MailService {
16
+ readonly service: string;
17
+ readonly baseUrl: string;
18
+ readonly username: string;
19
+ readonly password: string;
20
+ constructor(service: string, baseUrl: string, username: string, password: string);
21
+ send(customerId: number, recipients: Recipient[], subject: string, body: string, attachments: Attachment[], fromName?: string, replyTo?: string, meta?: Record<string, unknown>): Promise<MailSendResponse | undefined>;
22
+ }
23
+ export {};
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MailService = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const logger_1 = require("./logger");
9
+ class MailService {
10
+ service;
11
+ baseUrl;
12
+ username;
13
+ password;
14
+ constructor(service, baseUrl, username, password) {
15
+ this.service = service;
16
+ this.baseUrl = baseUrl;
17
+ this.username = username;
18
+ this.password = password;
19
+ this.service = service;
20
+ this.baseUrl = baseUrl;
21
+ this.username = username;
22
+ this.password = password;
23
+ }
24
+ async send(customerId, recipients, subject, body, attachments, fromName, replyTo, meta) {
25
+ if (recipients.length === 0) {
26
+ logger_1.logger.info("No recipients, not sending mail");
27
+ return;
28
+ }
29
+ try {
30
+ const response = await axios_1.default.post(`${this.baseUrl}/api/mail`, {
31
+ customerId,
32
+ fromName,
33
+ replyTo,
34
+ recipients,
35
+ content: {
36
+ type: "html",
37
+ html: body,
38
+ subject,
39
+ attachments,
40
+ },
41
+ meta: {
42
+ ...meta,
43
+ service: this.service,
44
+ },
45
+ }, {
46
+ auth: {
47
+ username: this.username,
48
+ password: this.password,
49
+ },
50
+ });
51
+ return response.data;
52
+ }
53
+ catch (e) {
54
+ if (axios_1.default.isAxiosError(e) && e.response) {
55
+ if (e.code === "ECONNRESET") {
56
+ logger_1.logger.warn("socket hang up error detected, setting hook for retry");
57
+ throw e;
58
+ }
59
+ const { status, data } = e.response;
60
+ logger_1.logger.error("Failed to send email", { response: { status, data } });
61
+ throw new Error(`Failed to send email. ${data.message}`);
62
+ }
63
+ const error = e;
64
+ logger_1.logger.error("Failed to send email", { code: error.code, message: error.message });
65
+ throw new Error("Failed to send email");
66
+ }
67
+ }
68
+ }
69
+ exports.MailService = MailService;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ const vitest_1 = require("vitest");
40
+ const axios_1 = __importStar(require("axios"));
41
+ const nock_1 = __importDefault(require("nock"));
42
+ const MailService_1 = require("../MailService");
43
+ const logger_1 = require("../logger");
44
+ const baseUrl = "http://notifications.test";
45
+ const username = "user";
46
+ const password = "pass";
47
+ const recipients = [{ email: "someone@example.com", name: "Someone", type: "to" }];
48
+ const attachments = [
49
+ { name: "file.pdf", type: "application/pdf", data: "base64", inline: false },
50
+ ];
51
+ const newService = () => new MailService_1.MailService("some-service-name", baseUrl, username, password);
52
+ (0, vitest_1.describe)("MailService", () => {
53
+ (0, vitest_1.afterEach)(() => {
54
+ nock_1.default.cleanAll();
55
+ vitest_1.vi.restoreAllMocks();
56
+ });
57
+ (0, vitest_1.test)("does not send when there are no recipients", async () => {
58
+ const infoSpy = vitest_1.vi.spyOn(logger_1.logger, "info").mockImplementation(() => logger_1.logger);
59
+ const postSpy = vitest_1.vi.spyOn(axios_1.default, "post");
60
+ const result = await newService().send(1, [], "Subject", "<p>Body</p>", attachments);
61
+ (0, vitest_1.expect)(result).toBeUndefined();
62
+ (0, vitest_1.expect)(postSpy).not.toHaveBeenCalled();
63
+ (0, vitest_1.expect)(infoSpy).toHaveBeenCalledWith("No recipients, not sending mail");
64
+ });
65
+ (0, vitest_1.test)("sends mail and returns the response data", async () => {
66
+ let requestBody;
67
+ const apiMock = (0, nock_1.default)(baseUrl)
68
+ .post("/api/mail", (body) => {
69
+ requestBody = body;
70
+ return true;
71
+ })
72
+ .basicAuth({ user: username, pass: password })
73
+ .reply(200, { id: "mail-123" });
74
+ const result = await newService().send(42, recipients, "Hello", "<p>Body</p>", attachments, "MoreApp", "reply@example.com", { correlationId: "abc" });
75
+ (0, vitest_1.expect)(result).toEqual({ id: "mail-123" });
76
+ (0, vitest_1.expect)(requestBody).toEqual({
77
+ customerId: 42,
78
+ fromName: "MoreApp",
79
+ replyTo: "reply@example.com",
80
+ recipients,
81
+ content: {
82
+ type: "html",
83
+ html: "<p>Body</p>",
84
+ subject: "Hello",
85
+ attachments,
86
+ },
87
+ meta: {
88
+ correlationId: "abc",
89
+ service: "some-service-name",
90
+ },
91
+ });
92
+ apiMock.done();
93
+ });
94
+ (0, vitest_1.test)("throws with the server message on an error response", async () => {
95
+ vitest_1.vi.spyOn(logger_1.logger, "error").mockImplementation(() => logger_1.logger);
96
+ const apiMock = (0, nock_1.default)(baseUrl).post("/api/mail").reply(400, { message: "Invalid recipient" });
97
+ await (0, vitest_1.expect)(newService().send(1, recipients, "Subject", "<p>Body</p>", attachments)).rejects.toThrow("Failed to send email. Invalid recipient");
98
+ apiMock.done();
99
+ });
100
+ (0, vitest_1.test)("rethrows the original error on ECONNRESET so the caller can retry", async () => {
101
+ vitest_1.vi.spyOn(logger_1.logger, "warn").mockImplementation(() => logger_1.logger);
102
+ const econnreset = new axios_1.AxiosError("socket hang up", "ECONNRESET");
103
+ econnreset.response = {
104
+ status: 500,
105
+ data: {},
106
+ statusText: "",
107
+ headers: {},
108
+ config: {},
109
+ };
110
+ vitest_1.vi.spyOn(axios_1.default, "post").mockRejectedValue(econnreset);
111
+ await (0, vitest_1.expect)(newService().send(1, recipients, "Subject", "<p>Body</p>", attachments)).rejects.toBe(econnreset);
112
+ });
113
+ (0, vitest_1.test)("throws a generic error for non-axios failures", async () => {
114
+ vitest_1.vi.spyOn(logger_1.logger, "error").mockImplementation(() => logger_1.logger);
115
+ vitest_1.vi.spyOn(axios_1.default, "post").mockRejectedValue(new Error("boom"));
116
+ await (0, vitest_1.expect)(newService().send(1, recipients, "Subject", "<p>Body</p>", attachments)).rejects.toThrow("Failed to send email");
117
+ });
118
+ (0, vitest_1.test)("throws a generic error for an axios error without a response", async () => {
119
+ vitest_1.vi.spyOn(logger_1.logger, "error").mockImplementation(() => logger_1.logger);
120
+ // An axios error with no `response` (e.g. a timeout / connection failure)
121
+ // should fall through to the generic error path.
122
+ vitest_1.vi.spyOn(axios_1.default, "post").mockRejectedValue(new axios_1.AxiosError("timeout", "ETIMEDOUT"));
123
+ await (0, vitest_1.expect)(newService().send(1, recipients, "Subject", "<p>Body</p>", attachments)).rejects.toThrow("Failed to send email");
124
+ });
125
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moreapp/common-nodejs",
3
- "version": "0.13.1",
3
+ "version": "0.13.2",
4
4
  "license": "UNLICENSED",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",