UNPKG

@plunk/node

Version:

Official Node.js library for useplunk.com

80 lines (79 loc) 3.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Plunk = void 0; const tslib_1 = require("tslib"); const NotFound_1 = require("../errors/NotFound"); const TokenError_1 = require("../errors/TokenError"); class Plunk { constructor(key, options = {}) { /** * Resources */ this.events = { /** * Publishes an event to Plunk * @param {string} event.event - The event you want to publish * @param {string} event.email - The email associated with this event * @param {Object=} event.data - The user data associated with this event * @param {boolean=true} event.subscribed - Whether the user is subscribed to marketing emails */ track: (event) => tslib_1.__awaiter(this, void 0, void 0, function* () { return yield this.fetch({ method: "POST", url: "track", json: Object.assign({}, event), }); }), }; this.emails = { /** * Sends a transactional email with Plunk * * @param {string} body.to - The email you want to send to * @param {string} body.subject - The subject of the email * @param {string} body.body - The body of the email * @param {string=} body.from - The email you want to send from * @param {string=} body.name - The name you want to send as * @param {string=html} body.type - The type of email you want to send * @param {boolean=false} body.subscribed - Whether the user is subscribed to marketing emails */ send: (body) => tslib_1.__awaiter(this, void 0, void 0, function* () { return yield this.fetch({ method: "POST", url: "send", json: Object.assign({}, body), }); }), }; this.key = key; this.apiUrl = options.baseUrl || "https://api.useplunk.com/v1/"; } fetch(_a) { var _b; var { json, url } = _a, options = tslib_1.__rest(_a, ["json", "url"]); return tslib_1.__awaiter(this, void 0, void 0, function* () { const res = yield fetch(new URL(url, this.apiUrl).toString(), Object.assign(Object.assign({}, options), { headers: Object.assign(Object.assign({ Authorization: `Bearer ${this.key}` }, (json && { "Content-Type": "application/json" })), options.headers), body: json ? JSON.stringify(json) : undefined })); const text = yield res.text(); const data = safeJsonParse(text); if ((res === null || res === void 0 ? void 0 : res.status) === 401) { throw new TokenError_1.TokenError(data === null || data === void 0 ? void 0 : data.message); } if ((res === null || res === void 0 ? void 0 : res.status) === 404) { throw new NotFound_1.NotFoundError(data === null || data === void 0 ? void 0 : data.message); } if (!res.ok) { throw new Error((_b = data === null || data === void 0 ? void 0 : data.message) !== null && _b !== void 0 ? _b : "Unknown API Error"); } return data; }); } } exports.Plunk = Plunk; function safeJsonParse(text) { try { return JSON.parse(text); } catch (e) { return text; } }