Hi all,
I wanted to share a script I've been working on recently, it allows you to use a normal integration flow as a template for a My API. This has the advantage that you can use all the visual builder and mapping tools to build your API, and then still run it synchronously.
It can use any webhook flow as a template, as long as it doesn't have branching.
To use simply create a new script in Integrator.io, paste in the code from below and change the flow id to the flow you want to use as a template. Then create a My API, selecting your new script and the flowRunner function:
import { request, exports, imports, flows } from 'integrator-api'
/*
* flowRunner function:
*
* This function loads the integrator.io flow that is defined on line 16
* and calls every lookup/import step in sequence, and does the response mapping.
* The data posted to the api is passed to the steps, any exports are not run.
* It does not support branching
*/
function flowRunner (options) {
var data = options.body;
var response = {log: {}};
var flow = flows.get("11cb00d30e1131d11823afe5"); //put your flow id here
console.info(`Executing MyAPI call on flow ${flow._id}`);
var finalData = flow.pageProcessors.reduce((flowData,step,i) => {
let ioResponse;
console.debug(`Step ${i}: ${step.type}`);
try {
if (step.type == "export") {
ioResponse = exports.run({ _id:step._exportId, data:flowData });
console.debug(`Ran export ${step._exportId}`);
} else if (step.type == "import") {
ioResponse = imports.run({ _id:step._importId, data:flowData });
console.debug(`Ran import ${step._importId}`);
}
//map response back into data.
step.responseMapping.fields.forEach(field => {
flowData[field.generate] = extractField(field.extract,ioResponse);
console.debug(`Mapped ${field.generate} ${field.extract} >> ${flowData[field.generate]}`);
});
}catch(e) {
ioResponse = JSON.stringify(e)
console.error(`Error: ${ioResponse}`)
}
response.log[i] = {};
response.log[i].response = ioResponse;
return flowData;
},data);
console.debug(JSON.stringify(finalData));
response.data = finalData;
return {
statusCode: 200,
headers: { },
body: response
}
}
function extractField(extractStr, responseObject) {
//split the extract into an array like [data 0 EmplName]
let extractArray = extractStr.split('.');
//traverse the response per entry of the array
return extractArray.reduce( (node,key) => {
return node[key];
},responseObject);
}
The script will return the data returned by the steps as a single-record 'page' of data, and will also return a log object showing the intermediate results from the individual steps.