Last active
August 29, 2017 18:07
-
-
Save sunnygleason/672762909518adc5718cebd527595764 to your computer and use it in GitHub Desktop.
PubNub SMS sender FUNCTION JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const INFOBIP_API_KEY = 'YOUR_API_KEY'; | |
const INFOBIP_API_URL = 'https://api.infobip.com/sms/1/text/single'; | |
const SUCCESSFUL_SMS_STATUS_GROUPS = [1, 3]; | |
const pubNub = require('pubnub'); | |
const xhr = require('xhr'); | |
function composeOptions(apiKey, body) { | |
return { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `App ${apiKey}`, | |
'User-Agent': 'APIv5_PUBNUB' | |
}, | |
body: JSON.stringify(body) | |
}; | |
} | |
function isSuccessfullySent(responseBody) { | |
return SUCCESSFUL_SMS_STATUS_GROUPS.indexOf(responseBody.messages[0].status.groupId) > -1; | |
} | |
function handleApiResponse(pubNubRequest, apiResponse) { | |
const httpStatus = apiResponse.status; | |
const responseBody = JSON.parse(apiResponse.body); | |
if (httpStatus === 200 && isSuccessfullySent(responseBody)) { | |
pubNubRequest.message.sent = responseBody; | |
pubNubRequest.message.sent.timestamp = new Date().toISOString(); | |
return pubNubRequest.ok(); | |
} else { | |
return pubNubRequest.abort('Message sending failed.'); | |
} | |
} | |
function handleSendingError(pubNubRequest, error) { | |
const message = error.message; | |
const fileName = error.fileName; | |
const lineNumber = error.lineNumber; | |
return pubNubRequest.abort('Failed to make API request to Infobip.'); | |
} | |
export default (pubNubRequest) => { | |
const to = pubNubRequest.message.to; | |
const text = pubNubRequest.message.text; | |
const from = pubNubRequest.message.from; | |
if (!to) return pubNubRequest.ok(); | |
const options = composeOptions(INFOBIP_API_KEY, {from, to, text}); | |
return xhr.fetch(INFOBIP_API_URL, options) | |
.then(handleApiResponse.bind(this, pubNubRequest)) | |
.catch(handleSendingError.bind(this, pubNubRequest)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment