2019-06-23 03:35:23 -07:00
|
|
|
import { IExecuteFunctions } from 'n8n-core';
|
|
|
|
import {
|
|
|
|
INodeExecutionData,
|
|
|
|
INodeType,
|
|
|
|
INodeTypeDescription,
|
|
|
|
} from 'n8n-workflow';
|
|
|
|
|
|
|
|
const { NodeVM } = require('vm2');
|
|
|
|
|
|
|
|
export class Function implements INodeType {
|
|
|
|
description: INodeTypeDescription = {
|
|
|
|
displayName: 'Function',
|
|
|
|
name: 'function',
|
|
|
|
icon: 'fa:code',
|
|
|
|
group: ['transform'],
|
|
|
|
version: 1,
|
2019-10-28 00:53:29 -07:00
|
|
|
description: 'Run custom function code which gets executed once and allows to add, remove, change and replace items.',
|
2019-06-23 03:35:23 -07:00
|
|
|
defaults: {
|
|
|
|
name: 'Function',
|
|
|
|
color: '#FF9922',
|
|
|
|
},
|
|
|
|
inputs: ['main'],
|
|
|
|
outputs: ['main'],
|
|
|
|
properties: [
|
|
|
|
{
|
|
|
|
displayName: 'Function',
|
|
|
|
name: 'functionCode',
|
|
|
|
typeOptions: {
|
|
|
|
alwaysOpenEditWindow: true,
|
2019-09-04 09:22:06 -07:00
|
|
|
editor: 'code',
|
2019-06-23 03:35:23 -07:00
|
|
|
rows: 10,
|
|
|
|
},
|
|
|
|
type: 'string',
|
|
|
|
default: 'items[0].json.myVariable = 1;\nreturn items;',
|
|
|
|
description: 'The JavaScript code to execute.',
|
2019-09-04 09:22:06 -07:00
|
|
|
noDataExpression: true,
|
2019-06-23 03:35:23 -07:00
|
|
|
},
|
|
|
|
],
|
|
|
|
};
|
|
|
|
|
|
|
|
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
|
|
|
|
// const item = this.getInputData();
|
|
|
|
let items = this.getInputData();
|
|
|
|
|
2019-08-01 13:55:33 -07:00
|
|
|
// Copy the items as they may get changed in the functions
|
|
|
|
items = JSON.parse(JSON.stringify(items));
|
|
|
|
|
2019-06-23 03:35:23 -07:00
|
|
|
// Define the global objects for the custom function
|
|
|
|
const sandbox = {
|
|
|
|
getNodeParameter: this.getNodeParameter,
|
2019-10-14 22:37:49 -07:00
|
|
|
getWorkflowStaticData: this.getWorkflowStaticData,
|
2019-06-23 03:35:23 -07:00
|
|
|
helpers: this.helpers,
|
|
|
|
items,
|
2019-09-04 05:53:39 -07:00
|
|
|
// To be able to access data of other items
|
|
|
|
$item: (index: number) => this.getWorkflowDataProxy(index),
|
2019-06-23 03:35:23 -07:00
|
|
|
};
|
|
|
|
|
2019-09-04 05:53:39 -07:00
|
|
|
// Make it possible to access data via $node, $parameter, ...
|
|
|
|
// By default use data from first item
|
|
|
|
Object.assign(sandbox, sandbox.$item(0));
|
|
|
|
|
2019-06-23 03:35:23 -07:00
|
|
|
const vm = new NodeVM({
|
|
|
|
console: 'inherit',
|
|
|
|
sandbox,
|
|
|
|
require: {
|
|
|
|
external: false,
|
|
|
|
root: './',
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// Get the code to execute
|
|
|
|
const functionCode = this.getNodeParameter('functionCode', 0) as string;
|
|
|
|
|
|
|
|
try {
|
|
|
|
// Execute the function code
|
|
|
|
items = await vm.run(`module.exports = async function() {${functionCode}}()`);
|
|
|
|
} catch (e) {
|
|
|
|
return Promise.reject(e);
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.prepareOutputData(items);
|
|
|
|
}
|
|
|
|
}
|