This repository has been archived on 2022-03-31. You can view files and clone it, but cannot push or open issues or pull requests.
cic-ussd-e2e/lib.js

44 lines
942 B
JavaScript

const crypto = require("crypto");
const phin = require("phin");
const conf = require("./config");
async function ussdClient(phone, sessionId, input = "") {
const requestOptions = {
url: conf.ussd.endpoint,
method: "POST",
parse: "string",
timeout: conf.ussd.timeout,
form: {
sessionId: sessionId,
// Get from a conf file, then pass as a param
phoneNumber: phone,
serviceCode: conf.ussd.serviceCode,
text: input,
},
};
try {
const { body } = await phin(requestOptions);
if (body.length > 1) {
return {
code: body.slice(0, 3),
text: body.slice(4),
};
}
throw new Error("EMPTY_BODY");
} catch (error) {
console.log(error);
}
}
function newSession() {
return crypto.randomBytes(16).toString("hex");
}
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
module.exports = { ussdClient, newSession, wait };