Hi
I am building an app where I use VM2 to create another version of the javascript editor that has my custom functions inside.
I am using a search step to do this, but I am getting the error
Invalid API Response: - Results must be an array, got: undefined, (undefined)
Here is my code:
const vm2 = require("vm2");
const moment = require("moment");
const fetch = require("node-fetch");
const runCode = async (code, inputData) => {
console.log(code);
console.log(inputData);
const vm = new vm2.NodeVM({
sandbox: {
moment,
fetch,
inputData,
},
});
const wrapper = `module.exports = (async function run() {
let output;
${code}
return output;
})()`;
const result = await vm.run(wrapper);
return result;
};
const perform = async (z, bundle) => {
console.log(z);
console.log(bundle);
const inputData = bundle.inputData;
const code = bundle.inputData.code;
const result = await runCode(code, inputData);
return result;
};
module.exports = {
key: "runJsCode",
noun: "Code",
display: {
label: "Run JavaScript Code",
description: "Runs JavaScript code",
},
operation: {
inputFields: [
{
key: "inputData",
label: "Input Data",
dict: true,
helpText:
"What input data should we provide to your code (as strings) via an object set to a variable named `inputData`?",
},
async (z, bundle) => {
return [
{
key: "code",
label: "Code",
type: "code",
language: "javascript",
default:
'// this is wrapped in an `async` function\n// you can use await throughout the function\n\noutput = [{id: 123, hello: "world"}];',
required: true,
},
];
},
],
perform,
sample: {
id: 1,
},
},
};
and here is my package.json file:
{
"name": "js-editor",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --testTimeout 10000"
},
"dependencies": {
"moment": "^2.29.1",
"node-fetch": "^2.6.1",
"vm2": "^3.9.2",
"zapier-platform-core": "10.1.2"
},
"devDependencies": {
"jest": "^25.5.3"
},
"private": true
}
Best answer by ikbelkirasan
Well, the `code` field type isn’t documented and it’s only used by the official code step app. I used it to enable syntax highlighting for JavaScript code.
However, that’s not the problem. The error is trying to tell you that the response of this step is undefined instead of an array. So, maybe you forgot to set the output value? Also, I suggest using return [...] instead of output = [...].
Hope this helps!