-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
119 lines (102 loc) · 2.58 KB
/
index.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const fetch = require('node-fetch')
const BASE_URL = "https://kmxl1.api.infobip.com"
const endpoints = Object.freeze({
'sms-single': 'sms/1/text/single',
'sms-multi': 'sms/2/text/single',
'sms-preview': 'sms/1/preview'
})
function InfobipAPI (auth) {
_auth = auth || {}
_options = {}
_authShape = {
username: null,
password: null
}
function _checkIfNotEmpty (payload, shape) {
Object.keys(shape).forEach(key => {
const optional =
shape[key] &&
shape[key].hasOwnProperty('optional') &&
shape[key].optional
if (!optional && !payload[key]) {
throw new Error(`'${key}' is required`)
}
})
}
function _buildAuthorizationHeader () {
let buffer = new Buffer.from(_auth.username + ':' + _auth.password)
return `Basic ${buffer.toString('base64')}`
}
function _buildURL (endpoint) {
return `${BASE_URL}/${endpoints[endpoint]}`
}
function _cleanup () {
_options = {}
}
// public members
this.from = function (from) {
_options = Object.assign({}, _options, { from })
return this
}
this.to = function (to) {
_options = Object.assign({}, _options, { to })
return this
}
this.message = function (text) {
_options = Object.assign({}, _options, { text })
return this
}
this.transliteration = function (language) {
_options = Object.assign({}, _options, { transliteration: language })
return this
}
this.send = function (endpoint = 'sms-single') {
_checkIfNotEmpty(_options, {
from: null,
to: null,
text: null,
transliteration: {
optional: true
}
})
_checkIfNotEmpty(_auth, _authShape)
const URL = _buildURL(endpoint)
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: _buildAuthorizationHeader()
}
return fetch(URL, {
method: 'POST',
body: JSON.stringify(_options),
headers
}).then(res => {
_cleanup()
return res.json()
})
}
this.preview = function () {
_checkIfNotEmpty(_options, {
text: null,
transliteration: {
optional: true
}
})
_checkIfNotEmpty(_auth, _authShape)
const URL = _buildURL('sms-preview')
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: _buildAuthorizationHeader()
}
return fetch(URL, {
method: 'POST',
body: JSON.stringify(_options),
headers
}).then(res => {
_cleanup()
return res.json()
})
}
}
module.exports = InfobipAPI