Last active
March 16, 2020 13:03
-
-
Save ForeSoftCorp/e724fc94651436fab2486f57fd00d170 to your computer and use it in GitHub Desktop.
Twilio function to dump incoming SMS information to TeamDesk
This file contains hidden or 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
/* | |
* 1. Requires reference to got 9.6.0, see https://www.twilio.com/docs/runtime/functions/packages | |
* 2. Please do not forget to patch config variable with your database settings: dbID, table and field names | |
*/ | |
exports.handler = function(context, event, callback) { | |
"use strict"; | |
var config = { | |
host: "www.teamdesk.net", | |
dbId: "12345", | |
apiToken: "12345678901234567890123456789012", | |
tableName: "Message", | |
// left - event field, right - TeamDesk column | |
fieldMap: { | |
"From": "From", | |
"To": "To", | |
"Body": "Body", | |
"SmsStatus": "Status" | |
} | |
}; | |
console.log(JSON.stringify(event)); | |
// build API URL | |
var apiURL = "https://" + config.host + "/secure/api/v2/" + config.dbId + "/" + | |
config.apiToken + "/" + encodeURIComponent(config.tableName) + "/create.json"; | |
// build requestPayload | |
var createRequestData = {}; | |
for(var key in config.fieldMap){ | |
createRequestData[config.fieldMap[key]] = event[key]; | |
} | |
// ready to send data to TeamDesk | |
var got = require('got'); | |
got .post(apiURL, { body: [createRequestData], throwHttpErrors: false, json: true, responseType: 'json' }) | |
.then(function(response) { | |
var data = response.body; | |
if(response.statusCode == 200 && data[0].status < 300) { | |
callback(); | |
} | |
else { | |
var err = response.statusCode >= 300 ? data : data[0].errors[0]; | |
var message = "TD>ERROR " + err.error + "." + err.code + ": " + (err.source ? err.source + ": " : "") + err.message; | |
callback(message); | |
} | |
}) | |
.catch(function(error) { | |
callback(error); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment