-
Notifications
You must be signed in to change notification settings - Fork 1
/
sms.mjs
62 lines (56 loc) · 2.07 KB
/
sms.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { log as _log, need, throwError, trim } from './utilitas.mjs';
import { promisify } from 'util';
const defaultTeleSignApi = 'https://rest-api.telesign.com';
const defaultTimeout = 1000 * 10 // 10 secs
const log = (content) => _log(content, import.meta.url);
let from, provider, client, sendFunc;
const _NEED = ['twilio', 'telesignsdk'];
const throwInvalidProvider = (message, status) =>
throwError(message || 'Invalid SMS provider.', status || 500);
const init = async (options) => {
if (options) {
provider = trim(options.provider, { case: 'UP' });
let engine;
switch (provider) {
case 'TWILIO':
assert(from = options.phoneNumber,
'Sender phone number is required.', 500);
engine = await need('twilio');
client = new engine(options.accountSid, options.authToken);
break;
case 'TELESIGN':
engine = await need('telesignsdk');
client = new engine(
options.customerId, options.apiKey,
options.rest_endpoint || defaultTeleSignApi,
options.timeout || defaultTimeout
);
sendFunc = promisify((phone, message, msgType, cbf) =>
client.sms.message(cbf, phone, message, msgType));
break;
default:
throwInvalidProvider();
}
if (!options.silent) {
log(`Initialized: ${options.accountSid
|| options.customerId} via ${provider}.`);
}
}
assert(client, 'SMS client has not been initialized.', 501);
return client;
};
const send = async (to, body) => {
assert(to, 'Invalid phone number.', 500);
assert(body, 'Message is required.', 500);
switch (provider) {
case 'TWILIO': return await client.messages.create({ from, to, body });
case 'TELESIGN': return await sendFunc(to, body, 'ARN');
default: throwInvalidProvider();
}
};
export default init;
export {
_NEED,
init,
send,
};