/** @module services.ona */
const utils = require('../utils/Utils.js');
const request = require('../../lib/HTTP.js');
const config = require('../../config/Config.js');
const aggregate = require('../../lib/Aggregate.js');
const uuidV4 = require('uuid/v4');
const {onaOrg, onaApiToken} = config;
const onaSubmissionEndpointURL = `https://api.ona.io/${onaOrg}/submission`;
/**
* send a POST to Ona's submission endpoint.
* We only need this function for its side effects therefore it lacks a
* return statemnt.
* @param {object} payload
* @param {string} url - change the URL for testing
* @return {promise} a promise holding the request response
*/
function postSubmissionToOna(payload, url = onaSubmissionEndpointURL) {
return request(
url,
{
method: 'POST',
body: JSON.stringify(payload),
headers: {
Authorization: `Token ${onaApiToken}`,
'Content-Type': 'application/json',
},
},
'POST submission to Ona: '
);
}
/**
* Generate a submission and POST it to Ona
* We only need this function for its side effects therefore it lacks a
* return statemnt.
* @param {object} convo A conversation object generated by botkit.
* @param {object} extraFields - Object containing {name, idString}
* name - Space seperated name of the respondent e.g John Doe
* idString - Ona form idString
* other fields thay you want in your submission
* @param {string} url - change the URL for testing
* @return {promise} a promise holding the request response
*/
function genAndPostSubmissionToOna(
convo,
extraFields,
url = onaSubmissionEndpointURL
) {
const aggregatedConvo = aggregate.aggregate(convo);
const submission = aggregate.genOnaSubmission(aggregatedConvo);
const [firstName, lastName] = extraFields.name.split(' ');
// Generate uuid if it isn't in extra fields
const uuid = extraFields.uuid ? extraFields.uuid : uuidV4();
submission.submission.meta = {instanceID: `uuid:${uuid}`};
submission.id = extraFields.idString;
submission.submission.first_name = firstName;
submission.submission.last_name = lastName;
submission.submission.messenger_id = aggregatedConvo.psid;
delete extraFields['name'];
delete extraFields['idString'];
submission.submission = utils.mergeObjects(
submission.submission,
extraFields
);
return postSubmissionToOna(submission, url);
}
module.exports = {
genAndPostSubmissionToOna,
};