@codebucket/sms
Version:
SMS module
56 lines (55 loc) • 2.63 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Msg91Provider = void 0;
const axios_1 = __importDefault(require("axios"));
const BaseProvider_1 = require("./BaseProvider");
class Msg91Provider extends BaseProvider_1.BaseProvider {
constructor(cfg) {
super();
this.cfg = cfg;
this.textUrl = cfg.textUrl || 'https://api.msg91.com/api/v2/sendsms';
this.flowUrl = cfg.flowUrl || 'https://control.msg91.com/api/v5/flow';
}
async send(opts) {
const { to, type = 'text', content = '', templateId, shortUrl, shortUrlExpiry, realTimeResponse } = opts;
let { variables = [], } = opts;
if (Array.isArray(variables)) {
let tempVariables = {};
for (let i = 0; i < variables.length; i++) {
tempVariables[`var${i + 1}`] = variables[i];
}
variables = tempVariables;
}
switch (type) {
case 'template': {
const recipients = to.map(num => ({ mobiles: num, ...variables }));
let payload = { template_id: templateId, recipients, short_url: 0 };
if (shortUrl)
payload = { ...payload, short_url: shortUrl, };
if (shortUrlExpiry)
payload = { ...payload, short_url_expiry: shortUrlExpiry, };
if (realTimeResponse)
payload = { ...payload, realTimeResponse };
const headers = { 'accept': 'application/json', 'content-type': 'application/json', 'authkey': this.cfg.authKey };
return (await axios_1.default.post(this.flowUrl, payload, { headers })).data;
}
case 'text':
case 'bulk':
case 'otp':
default: {
const text = this.interpolate(content, variables);
const smsArr = to.map(num => ({ message: text, to: [num] }));
const payload = { sender: this.cfg.senderId, route: this.cfg.route, country: this.cfg.country, sms: smsArr };
const headers = { 'accept': 'application/json', 'content-type': 'application/json', 'authkey': this.cfg.authKey };
return (await axios_1.default.post(this.textUrl, payload, { headers })).data;
}
}
}
interpolate(t, vars) {
return t.replace(/{{(\w+)}}/g, (_, k) => vars[k] != null ? String(vars[k]) : '');
}
}
exports.Msg91Provider = Msg91Provider;