🔀 Merge branch 'Remove-executeSingle' of https://github.com/MedAliMarz/n8n into MedAliMarz-Remove-executeSingle

This commit is contained in:
Jan Oberhauser 2021-03-29 11:11:03 +02:00
commit e48f555f07
7 changed files with 591 additions and 520 deletions

View file

@ -1,6 +1,6 @@
import {
BINARY_ENCODING,
IExecuteSingleFunctions,
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
@ -948,291 +948,301 @@ export class EditImage implements INodeType {
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: INodeExecutionData[] = [];
const length = items.length as unknown as number;
let item: INodeExecutionData;
async executeSingle(this: IExecuteSingleFunctions): Promise<INodeExecutionData> {
const item = this.getInputData();
for (let itemIndex = 0; itemIndex < length; itemIndex++) {
item = items[itemIndex];
const operation = this.getNodeParameter('operation', 0) as string;
const dataPropertyName = this.getNodeParameter('dataPropertyName') as string;
const options = this.getNodeParameter('options', {}) as IDataObject;
const operation = this.getNodeParameter('operation', itemIndex) as string;
const dataPropertyName = this.getNodeParameter('dataPropertyName', itemIndex) as string;
const cleanupFunctions: Array<() => void> = [];
const options = this.getNodeParameter('options', itemIndex,{}) as IDataObject;
let gmInstance: gm.State;
const cleanupFunctions: Array<() => void> = [];
const requiredOperationParameters: {
[key: string]: string[],
} = {
blur: [
'blur',
'sigma',
],
border: [
'borderColor',
'borderWidth',
'borderHeight',
],
create: [
'backgroundColor',
'height',
'width',
],
crop: [
'height',
'positionX',
'positionY',
'width',
],
composite: [
'dataPropertyNameComposite',
'positionX',
'positionY',
],
draw: [
'color',
'cornerRadius',
'endPositionX',
'endPositionY',
'primitive',
'startPositionX',
'startPositionY',
],
information: [],
resize: [
'height',
'resizeOption',
'width',
],
rotate: [
'backgroundColor',
'rotate',
],
shear: [
'degreesX',
'degreesY',
],
text: [
'font',
'fontColor',
'fontSize',
'lineLength',
'positionX',
'positionY',
'text',
],
};
let gmInstance: gm.State;
let operations: IDataObject[] = [];
if (operation === 'multiStep') {
// Operation parameters are already in the correct format
const operationsData = this.getNodeParameter('operations', { operations: [] }) as IDataObject;
operations = operationsData.operations as IDataObject[];
} else {
// Operation parameters have to first get collected
const operationParameters: IDataObject = {};
requiredOperationParameters[operation].forEach(parameterName => {
try {
operationParameters[parameterName] = this.getNodeParameter(parameterName);
} catch (e) {}
});
const requiredOperationParameters: {
[key: string]: string[],
} = {
blur: [
'blur',
'sigma',
],
border: [
'borderColor',
'borderWidth',
'borderHeight',
],
create: [
'backgroundColor',
'height',
'width',
],
crop: [
'height',
'positionX',
'positionY',
'width',
],
composite: [
'dataPropertyNameComposite',
'positionX',
'positionY',
],
draw: [
'color',
'cornerRadius',
'endPositionX',
'endPositionY',
'primitive',
'startPositionX',
'startPositionY',
],
information: [],
resize: [
'height',
'resizeOption',
'width',
],
rotate: [
'backgroundColor',
'rotate',
],
shear: [
'degreesX',
'degreesY',
],
text: [
'font',
'fontColor',
'fontSize',
'lineLength',
'positionX',
'positionY',
'text',
],
};
operations = [
{
operation,
...operationParameters,
},
];
}
if (operations[0].operation !== 'create') {
// "create" generates a new image so does not require any incoming data.
if (item.binary === undefined) {
throw new Error('Item does not contain any binary data.');
}
if (item.binary[dataPropertyName as string] === undefined) {
throw new Error(`Item does not contain any binary data with the name "${dataPropertyName}".`);
}
gmInstance = gm(Buffer.from(item.binary![dataPropertyName as string].data, BINARY_ENCODING));
gmInstance = gmInstance.background('transparent');
}
if (operation === 'information') {
// Just return the information
const imageData = await new Promise<IDataObject>((resolve, reject) => {
gmInstance = gmInstance.identify((error, imageData) => {
if (error) {
reject(error);
return;
}
resolve(imageData as unknown as IDataObject);
let operations: IDataObject[] = [];
if (operation === 'multiStep') {
// Operation parameters are already in the correct format
const operationsData = this.getNodeParameter('operations', itemIndex ,{ operations: [] }) as IDataObject;
operations = operationsData.operations as IDataObject[];
} else {
// Operation parameters have to first get collected
const operationParameters: IDataObject = {};
requiredOperationParameters[operation].forEach(parameterName => {
try {
operationParameters[parameterName] = this.getNodeParameter(parameterName, itemIndex);
} catch (e) {}
});
});
item.json = imageData;
return item;
}
operations = [
{
operation,
...operationParameters,
},
];
}
for (let i = 0; i < operations.length; i++) {
const operationData = operations[i];
if (operationData.operation === 'blur') {
gmInstance = gmInstance!.blur(operationData.blur as number, operationData.sigma as number);
} else if (operationData.operation === 'border') {
gmInstance = gmInstance!.borderColor(operationData.borderColor as string).border(operationData.borderWidth as number, operationData.borderHeight as number);
} else if (operationData.operation === 'composite') {
const positionX = operationData.positionX as number;
const positionY = operationData.positionY as number;
const geometryString = (positionX >= 0 ? '+' : '') + positionX + (positionY >= 0 ? '+' : '') + positionY;
if (item.binary![operationData.dataPropertyNameComposite as string] === undefined) {
throw new Error(`Item does not contain any binary data with the name "${operationData.dataPropertyNameComposite}".`);
if (operations[0].operation !== 'create') {
// "create" generates a new image so does not require any incoming data.
if (item.binary === undefined) {
throw new Error('Item does not contain any binary data.');
}
const { fd, path, cleanup } = await file();
cleanupFunctions.push(cleanup);
await fsWriteFileAsync(fd, Buffer.from(item.binary![operationData.dataPropertyNameComposite as string].data, BINARY_ENCODING));
if (operations[0].operation === 'create') {
// It seems like if the image gets created newly we have to create a new gm instance
// else it fails for some reason
gmInstance = gm(gmInstance!.stream('png')).geometry(geometryString).composite(path);
} else {
gmInstance = gmInstance!.geometry(geometryString).composite(path);
if (item.binary[dataPropertyName as string] === undefined) {
throw new Error(`Item does not contain any binary data with the name "${dataPropertyName}".`);
}
if (operations.length !== i + 1) {
// If there are other operations after the current one create a new gm instance
// because else things do get messed up
gmInstance = gm(gmInstance.stream());
}
} else if (operationData.operation === 'create') {
gmInstance = gm(operationData.width as number, operationData.height as number, operationData.backgroundColor as string);
if (!options.format) {
options.format = 'png';
}
} else if (operationData.operation === 'crop') {
gmInstance = gmInstance!.crop(operationData.width as number, operationData.height as number, operationData.positionX as number, operationData.positionY as number);
} else if (operationData.operation === 'draw') {
gmInstance = gmInstance!.fill(operationData.color as string);
gmInstance = gm(Buffer.from(item.binary![dataPropertyName as string].data, BINARY_ENCODING));
gmInstance = gmInstance.background('transparent');
}
if (operationData.primitive === 'line') {
gmInstance = gmInstance.drawLine(operationData.startPositionX as number, operationData.startPositionY as number, operationData.endPositionX as number, operationData.endPositionY as number);
} else if (operationData.primitive === 'rectangle') {
gmInstance = gmInstance.drawRectangle(operationData.startPositionX as number, operationData.startPositionY as number, operationData.endPositionX as number, operationData.endPositionY as number, operationData.cornerRadius as number || undefined);
}
} else if (operationData.operation === 'resize') {
const resizeOption = operationData.resizeOption as string;
// By default use "maximumArea"
let option: gm.ResizeOption = '@';
if (resizeOption === 'ignoreAspectRatio') {
option = '!';
} else if (resizeOption === 'minimumArea') {
option = '^';
} else if (resizeOption === 'onlyIfSmaller') {
option = '<';
} else if (resizeOption === 'onlyIfLarger') {
option = '>';
} else if (resizeOption === 'percent') {
option = '%';
}
gmInstance = gmInstance!.resize(operationData.width as number, operationData.height as number, option);
} else if (operationData.operation === 'rotate') {
gmInstance = gmInstance!.rotate(operationData.backgroundColor as string, operationData.rotate as number);
} else if (operationData.operation === 'shear') {
gmInstance = gmInstance!.shear(operationData.degreesX as number, operationData.degreesY as number);
} else if (operationData.operation === 'text') {
// Split the text in multiple lines
const lines: string[] = [];
let currentLine = '';
(operationData.text as string).split('\n').forEach((textLine: string) => {
textLine.split(' ').forEach((textPart: string) => {
if ((currentLine.length + textPart.length + 1) > (operationData.lineLength as number)) {
lines.push(currentLine.trim());
currentLine = `${textPart} `;
if (operation === 'information') {
// Just return the information
const imageData = await new Promise<IDataObject>((resolve, reject) => {
gmInstance = gmInstance.identify((error:any, imageData:any) => {
if (error) {
reject(error);
return;
}
currentLine += `${textPart} `;
resolve(imageData as unknown as IDataObject);
});
lines.push(currentLine.trim());
currentLine = '';
});
// Combine the lines to a single string
const renderText = lines.join('\n');
const font = options.font || operationData.font;
if (font && font !== 'default') {
gmInstance = gmInstance!.font(font as string);
}
gmInstance = gmInstance!
.fill(operationData.fontColor as string)
.fontSize(operationData.fontSize as number)
.drawText(operationData.positionX as number, operationData.positionY as number, renderText);
item.json = imageData;
returnData.push(item);
}
}
const newItem: INodeExecutionData = {
json: item.json,
binary: {},
};
for (let i = 0; i < operations.length; i++) {
const operationData = operations[i];
if (operationData.operation === 'blur') {
gmInstance = gmInstance!.blur(operationData.blur as number, operationData.sigma as number);
} else if (operationData.operation === 'border') {
gmInstance = gmInstance!.borderColor(operationData.borderColor as string).border(operationData.borderWidth as number, operationData.borderHeight as number);
} else if (operationData.operation === 'composite') {
const positionX = operationData.positionX as number;
const positionY = operationData.positionY as number;
if (item.binary !== undefined) {
// Create a shallow copy of the binary data so that the old
// data references which do not get changed still stay behind
// but the incoming data does not get changed.
Object.assign(newItem.binary, item.binary);
// Make a deep copy of the binary data we change
if (newItem.binary![dataPropertyName as string]) {
newItem.binary![dataPropertyName as string] = JSON.parse(JSON.stringify(newItem.binary![dataPropertyName as string]));
}
}
const geometryString = (positionX >= 0 ? '+' : '') + positionX + (positionY >= 0 ? '+' : '') + positionY;
if (newItem.binary![dataPropertyName as string] === undefined) {
newItem.binary![dataPropertyName as string] = {
data: '',
mimeType: '',
};
}
if (options.quality !== undefined) {
gmInstance = gmInstance!.quality(options.quality as number);
}
if (options.format !== undefined) {
gmInstance = gmInstance!.setFormat(options.format as string);
newItem.binary![dataPropertyName as string].fileExtension = options.format as string;
newItem.binary![dataPropertyName as string].mimeType = `image/${options.format}`;
const fileName = newItem.binary![dataPropertyName as string].fileName;
if (fileName && fileName.includes('.')) {
newItem.binary![dataPropertyName as string].fileName = fileName.split('.').slice(0, -1).join('.') + '.' + options.format;
}
}
if (options.fileName !== undefined) {
newItem.binary![dataPropertyName as string].fileName = options.fileName as string;
}
return new Promise<INodeExecutionData>((resolve, reject) => {
gmInstance
.toBuffer((error: Error | null, buffer: Buffer) => {
cleanupFunctions.forEach(async cleanup => await cleanup());
if (error) {
return reject(error);
if (item.binary![operationData.dataPropertyNameComposite as string] === undefined) {
throw new Error(`Item does not contain any binary data with the name "${operationData.dataPropertyNameComposite}".`);
}
newItem.binary![dataPropertyName as string].data = buffer.toString(BINARY_ENCODING);
const { fd, path, cleanup } = await file();
cleanupFunctions.push(cleanup);
await fsWriteFileAsync(fd, Buffer.from(item.binary![operationData.dataPropertyNameComposite as string].data, BINARY_ENCODING));
return resolve(newItem);
});
});
if (operations[0].operation === 'create') {
// It seems like if the image gets created newly we have to create a new gm instance
// else it fails for some reason
gmInstance = gm(gmInstance!.stream('png')).geometry(geometryString).composite(path);
} else {
gmInstance = gmInstance!.geometry(geometryString).composite(path);
}
if (operations.length !== i + 1) {
// If there are other operations after the current one create a new gm instance
// because else things do get messed up
gmInstance = gm(gmInstance.stream());
}
} else if (operationData.operation === 'create') {
gmInstance = gm(operationData.width as number, operationData.height as number, operationData.backgroundColor as string);
if (!options.format) {
options.format = 'png';
}
} else if (operationData.operation === 'crop') {
gmInstance = gmInstance!.crop(operationData.width as number, operationData.height as number, operationData.positionX as number, operationData.positionY as number);
} else if (operationData.operation === 'draw') {
gmInstance = gmInstance!.fill(operationData.color as string);
if (operationData.primitive === 'line') {
gmInstance = gmInstance.drawLine(operationData.startPositionX as number, operationData.startPositionY as number, operationData.endPositionX as number, operationData.endPositionY as number);
} else if (operationData.primitive === 'rectangle') {
gmInstance = gmInstance.drawRectangle(operationData.startPositionX as number, operationData.startPositionY as number, operationData.endPositionX as number, operationData.endPositionY as number, operationData.cornerRadius as number || undefined);
}
} else if (operationData.operation === 'resize') {
const resizeOption = operationData.resizeOption as string;
// By default use "maximumArea"
let option: gm.ResizeOption = '@';
if (resizeOption === 'ignoreAspectRatio') {
option = '!';
} else if (resizeOption === 'minimumArea') {
option = '^';
} else if (resizeOption === 'onlyIfSmaller') {
option = '<';
} else if (resizeOption === 'onlyIfLarger') {
option = '>';
} else if (resizeOption === 'percent') {
option = '%';
}
gmInstance = gmInstance!.resize(operationData.width as number, operationData.height as number, option);
} else if (operationData.operation === 'rotate') {
gmInstance = gmInstance!.rotate(operationData.backgroundColor as string, operationData.rotate as number);
} else if (operationData.operation === 'shear') {
gmInstance = gmInstance!.shear(operationData.degreesX as number, operationData.degreesY as number);
} else if (operationData.operation === 'text') {
// Split the text in multiple lines
const lines: string[] = [];
let currentLine = '';
(operationData.text as string).split('\n').forEach((textLine: string) => {
textLine.split(' ').forEach((textPart: string) => {
if ((currentLine.length + textPart.length + 1) > (operationData.lineLength as number)) {
lines.push(currentLine.trim());
currentLine = `${textPart} `;
return;
}
currentLine += `${textPart} `;
});
lines.push(currentLine.trim());
currentLine = '';
});
// Combine the lines to a single string
const renderText = lines.join('\n');
const font = options.font || operationData.font;
if (font && font !== 'default') {
gmInstance = gmInstance!.font(font as string);
}
gmInstance = gmInstance!
.fill(operationData.fontColor as string)
.fontSize(operationData.fontSize as number)
.drawText(operationData.positionX as number, operationData.positionY as number, renderText);
}
}
const newItem: INodeExecutionData = {
json: item.json,
binary: {},
};
if (item.binary !== undefined) {
// Create a shallow copy of the binary data so that the old
// data references which do not get changed still stay behind
// but the incoming data does not get changed.
Object.assign(newItem.binary, item.binary);
// Make a deep copy of the binary data we change
if (newItem.binary![dataPropertyName as string]) {
newItem.binary![dataPropertyName as string] = JSON.parse(JSON.stringify(newItem.binary![dataPropertyName as string]));
}
}
if (newItem.binary![dataPropertyName as string] === undefined) {
newItem.binary![dataPropertyName as string] = {
data: '',
mimeType: '',
};
}
if (options.quality !== undefined) {
gmInstance = gmInstance!.quality(options.quality as number);
}
if (options.format !== undefined) {
gmInstance = gmInstance!.setFormat(options.format as string);
newItem.binary![dataPropertyName as string].fileExtension = options.format as string;
newItem.binary![dataPropertyName as string].mimeType = `image/${options.format}`;
const fileName = newItem.binary![dataPropertyName as string].fileName;
if (fileName && fileName.includes('.')) {
newItem.binary![dataPropertyName as string].fileName = fileName.split('.').slice(0, -1).join('.') + '.' + options.format;
}
}
if (options.fileName !== undefined) {
newItem.binary![dataPropertyName as string].fileName = options.fileName as string;
}
returnData.push(await (new Promise<INodeExecutionData>((resolve, reject) => {
gmInstance
.toBuffer((error: Error | null, buffer: Buffer) => {
cleanupFunctions.forEach(async cleanup => await cleanup());
if (error) {
return reject(error);
}
newItem.binary![dataPropertyName as string].data = buffer.toString(BINARY_ENCODING);
return resolve(newItem);
});
})));
}
return this.prepareOutputData(returnData);
}
}

View file

@ -1,6 +1,6 @@
import {
BINARY_ENCODING,
IExecuteSingleFunctions,
IExecuteFunctions
} from 'n8n-core';
import {
IDataObject,
@ -124,84 +124,95 @@ export class EmailSend implements INodeType {
};
async executeSingle(this: IExecuteSingleFunctions): Promise<INodeExecutionData> {
const item = this.getInputData();
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const fromEmail = this.getNodeParameter('fromEmail') as string;
const toEmail = this.getNodeParameter('toEmail') as string;
const ccEmail = this.getNodeParameter('ccEmail') as string;
const bccEmail = this.getNodeParameter('bccEmail') as string;
const subject = this.getNodeParameter('subject') as string;
const text = this.getNodeParameter('text') as string;
const html = this.getNodeParameter('html') as string;
const attachmentPropertyString = this.getNodeParameter('attachments') as string;
const options = this.getNodeParameter('options', {}) as IDataObject;
const returnData: INodeExecutionData[] = [];
const length = items.length as unknown as number;
let item: INodeExecutionData;
const credentials = this.getCredentials('smtp');
for (let itemIndex = 0; itemIndex < length; itemIndex++) {
item = items[itemIndex];
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
const fromEmail = this.getNodeParameter('fromEmail', itemIndex) as string;
const toEmail = this.getNodeParameter('toEmail', itemIndex) as string;
const ccEmail = this.getNodeParameter('ccEmail', itemIndex) as string;
const bccEmail = this.getNodeParameter('bccEmail', itemIndex) as string;
const subject = this.getNodeParameter('subject', itemIndex) as string;
const text = this.getNodeParameter('text', itemIndex) as string;
const html = this.getNodeParameter('html', itemIndex) as string;
const attachmentPropertyString = this.getNodeParameter('attachments', itemIndex) as string;
const options = this.getNodeParameter('options', itemIndex, {}) as IDataObject;
const connectionOptions: SMTPTransport.Options = {
host: credentials.host as string,
port: credentials.port as number,
secure: credentials.secure as boolean,
};
const credentials = this.getCredentials('smtp');
if(credentials.user || credentials.password) {
// @ts-ignore
connectionOptions.auth = {
user: credentials.user as string,
pass: credentials.password as string,
};
}
if (options.allowUnauthorizedCerts === true) {
connectionOptions.tls = {
rejectUnauthorized: false,
};
}
const transporter = createTransport(connectionOptions);
// setup email data with unicode symbols
const mailOptions = {
from: fromEmail,
to: toEmail,
cc: ccEmail,
bcc: bccEmail,
subject,
text,
html,
};
if (attachmentPropertyString && item.binary) {
const attachments = [];
const attachmentProperties: string[] = attachmentPropertyString.split(',').map((propertyName) => {
return propertyName.trim();
});
for (const propertyName of attachmentProperties) {
if (!item.binary.hasOwnProperty(propertyName)) {
continue;
}
attachments.push({
filename: item.binary[propertyName].fileName || 'unknown',
content: Buffer.from(item.binary[propertyName].data, BINARY_ENCODING),
});
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
if (attachments.length) {
const connectionOptions: SMTPTransport.Options = {
host: credentials.host as string,
port: credentials.port as number,
secure: credentials.secure as boolean,
};
if(credentials.user || credentials.password) {
// @ts-ignore
mailOptions.attachments = attachments;
connectionOptions.auth = {
user: credentials.user as string,
pass: credentials.password as string,
};
}
if (options.allowUnauthorizedCerts === true) {
connectionOptions.tls = {
rejectUnauthorized: false,
};
}
const transporter = createTransport(connectionOptions);
// setup email data with unicode symbols
const mailOptions = {
from: fromEmail,
to: toEmail,
cc: ccEmail,
bcc: bccEmail,
subject,
text,
html,
};
if (attachmentPropertyString && item.binary) {
const attachments = [];
const attachmentProperties: string[] = attachmentPropertyString.split(',').map((propertyName) => {
return propertyName.trim();
});
for (const propertyName of attachmentProperties) {
if (!item.binary.hasOwnProperty(propertyName)) {
continue;
}
attachments.push({
filename: item.binary[propertyName].fileName || 'unknown',
content: Buffer.from(item.binary[propertyName].data, BINARY_ENCODING),
});
}
if (attachments.length) {
// @ts-ignore
mailOptions.attachments = attachments;
}
}
// Send the email
const info = await transporter.sendMail(mailOptions);
returnData.push({ json: info });
}
// Send the email
const info = await transporter.sendMail(mailOptions);
return { json: info };
return this.prepareOutputData(returnData);
}
}

View file

@ -1,4 +1,4 @@
import { IExecuteSingleFunctions } from 'n8n-core';
import { IExecuteFunctions } from 'n8n-core';
import {
IBinaryKeyData,
IDataObject,
@ -40,74 +40,84 @@ export class FunctionItem implements INodeType {
],
};
async executeSingle(this: IExecuteSingleFunctions): Promise<INodeExecutionData> {
let item = this.getInputData();
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
// Copy the items as they may get changed in the functions
item = JSON.parse(JSON.stringify(item));
const returnData: INodeExecutionData[] = [];
const length = items.length as unknown as number;
let item: INodeExecutionData;
// Define the global objects for the custom function
const sandbox = {
getBinaryData: (): IBinaryKeyData | undefined => {
return item.binary;
},
getNodeParameter: this.getNodeParameter,
getWorkflowStaticData: this.getWorkflowStaticData,
helpers: this.helpers,
item: item.json,
setBinaryData: (data: IBinaryKeyData) => {
item.binary = data;
},
};
for (let itemIndex = 0; itemIndex < length; itemIndex++) {
// Make it possible to access data via $node, $parameter, ...
const dataProxy = this.getWorkflowDataProxy();
Object.assign(sandbox, dataProxy);
item = items[itemIndex];
const options = {
console: 'inherit',
sandbox,
require: {
external: false as boolean | { modules: string[] },
builtin: [] as string[],
},
};
// Copy the items as they may get changed in the functions
item = JSON.parse(JSON.stringify(item));
if (process.env.NODE_FUNCTION_ALLOW_BUILTIN) {
options.require.builtin = process.env.NODE_FUNCTION_ALLOW_BUILTIN.split(',');
}
// Define the global objects for the custom function
const sandbox = {
getBinaryData: (): IBinaryKeyData | undefined => {
return item.binary;
},
getNodeParameter: this.getNodeParameter,
getWorkflowStaticData: this.getWorkflowStaticData,
helpers: this.helpers,
item: item.json,
setBinaryData: (data: IBinaryKeyData) => {
item.binary = data;
},
};
if (process.env.NODE_FUNCTION_ALLOW_EXTERNAL) {
options.require.external = { modules: process.env.NODE_FUNCTION_ALLOW_EXTERNAL.split(',') };
}
// Make it possible to access data via $node, $parameter, ...
const dataProxy = this.getWorkflowDataProxy(itemIndex);
Object.assign(sandbox, dataProxy);
const vm = new NodeVM(options);
const options = {
console: 'inherit',
sandbox,
require: {
external: false as boolean | { modules: string[] },
builtin: [] as string[],
},
};
// Get the code to execute
const functionCode = this.getNodeParameter('functionCode') as string;
if (process.env.NODE_FUNCTION_ALLOW_BUILTIN) {
options.require.builtin = process.env.NODE_FUNCTION_ALLOW_BUILTIN.split(',');
}
if (process.env.NODE_FUNCTION_ALLOW_EXTERNAL) {
options.require.external = { modules: process.env.NODE_FUNCTION_ALLOW_EXTERNAL.split(',') };
}
const vm = new NodeVM(options);
// Get the code to execute
const functionCode = this.getNodeParameter('functionCode', itemIndex) as string;
let jsonData: IDataObject;
try {
// Execute the function code
jsonData = await vm.run(`module.exports = async function() {${functionCode}}()`, __dirname);
} catch (e) {
return Promise.reject(e);
}
let jsonData: IDataObject;
try {
// Execute the function code
jsonData = await vm.run(`module.exports = async function() {${functionCode}}()`, __dirname);
} catch (e) {
return Promise.reject(e);
}
// Do very basic validation of the data
if (jsonData === undefined) {
throw new Error('No data got returned. Always an object has to be returned!');
}
// Do very basic validation of the data
if (jsonData === undefined) {
throw new Error('No data got returned. Always an object has to be returned!');
}
const returnItem: INodeExecutionData = {
json: jsonData,
};
const returnItem: INodeExecutionData = {
json: jsonData,
};
if (item.binary) {
returnItem.binary = item.binary;
}
return returnItem;
if (item.binary) {
returnItem.binary = item.binary;
}
returnData.push(returnItem);
}
return this.prepareOutputData(returnData);
}
}

View file

@ -1,6 +1,6 @@
import {
BINARY_ENCODING,
IExecuteSingleFunctions,
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
@ -105,80 +105,89 @@ export class Mailgun implements INodeType {
};
async executeSingle(this: IExecuteSingleFunctions): Promise<INodeExecutionData> {
const item = this.getInputData();
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: INodeExecutionData[] = [];
const length = items.length as unknown as number;
let item: INodeExecutionData;
const fromEmail = this.getNodeParameter('fromEmail') as string;
const toEmail = this.getNodeParameter('toEmail') as string;
const ccEmail = this.getNodeParameter('ccEmail') as string;
const bccEmail = this.getNodeParameter('bccEmail') as string;
const subject = this.getNodeParameter('subject') as string;
const text = this.getNodeParameter('text') as string;
const html = this.getNodeParameter('html') as string;
const attachmentPropertyString = this.getNodeParameter('attachments') as string;
for (let itemIndex = 0; itemIndex < length; itemIndex++) {
item = items[itemIndex];
const credentials = this.getCredentials('mailgunApi');
const fromEmail = this.getNodeParameter('fromEmail', itemIndex) as string;
const toEmail = this.getNodeParameter('toEmail', itemIndex) as string;
const ccEmail = this.getNodeParameter('ccEmail', itemIndex) as string;
const bccEmail = this.getNodeParameter('bccEmail', itemIndex) as string;
const subject = this.getNodeParameter('subject', itemIndex) as string;
const text = this.getNodeParameter('text', itemIndex) as string;
const html = this.getNodeParameter('html', itemIndex) as string;
const attachmentPropertyString = this.getNodeParameter('attachments', itemIndex) as string;
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
const credentials = this.getCredentials('mailgunApi');
const formData: IDataObject = {
from: fromEmail,
to: toEmail,
subject,
text,
html,
};
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
if (ccEmail.length !== 0) {
formData.cc = ccEmail;
}
if (bccEmail.length !== 0) {
formData.bcc = bccEmail;
}
const formData: IDataObject = {
from: fromEmail,
to: toEmail,
subject,
text,
html,
};
if (attachmentPropertyString && item.binary) {
if (ccEmail.length !== 0) {
formData.cc = ccEmail;
}
if (bccEmail.length !== 0) {
formData.bcc = bccEmail;
}
const attachments = [];
const attachmentProperties: string[] = attachmentPropertyString.split(',').map((propertyName) => {
return propertyName.trim();
});
if (attachmentPropertyString && item.binary) {
for (const propertyName of attachmentProperties) {
if (!item.binary.hasOwnProperty(propertyName)) {
continue;
}
attachments.push({
value: Buffer.from(item.binary[propertyName].data, BINARY_ENCODING),
options: {
filename: item.binary[propertyName].fileName || 'unknown',
},
const attachments = [];
const attachmentProperties: string[] = attachmentPropertyString.split(',').map((propertyName) => {
return propertyName.trim();
});
for (const propertyName of attachmentProperties) {
if (!item.binary.hasOwnProperty(propertyName)) {
continue;
}
attachments.push({
value: Buffer.from(item.binary[propertyName].data, BINARY_ENCODING),
options: {
filename: item.binary[propertyName].fileName || 'unknown',
},
});
}
if (attachments.length) {
// @ts-ignore
formData.attachment = attachments;
}
}
if (attachments.length) {
// @ts-ignore
formData.attachment = attachments;
}
}
const options = {
method: 'POST',
formData,
uri: `https://${credentials.apiDomain}/v3/${credentials.emailDomain}/messages`,
auth: {
user: 'api',
pass: credentials.apiKey as string,
},
json: true,
};
const options = {
method: 'POST',
formData,
uri: `https://${credentials.apiDomain}/v3/${credentials.emailDomain}/messages`,
auth: {
user: 'api',
pass: credentials.apiKey as string,
},
json: true,
};
const responseData = await this.helpers.request(options);
const responseData = await this.helpers.request(options);
return {
json: responseData,
};
returnData.push({
json: responseData,
});
}
return this.prepareOutputData(returnData)
}
}

View file

@ -1,4 +1,4 @@
import { IExecuteSingleFunctions } from 'n8n-core';
import { IExecuteFunctions } from 'n8n-core';
import {
INodeExecutionData,
INodeType,
@ -49,38 +49,46 @@ export class ReadBinaryFile implements INodeType {
};
async executeSingle(this: IExecuteSingleFunctions): Promise<INodeExecutionData> {
const item = this.getInputData();
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const dataPropertyName = this.getNodeParameter('dataPropertyName') as string;
const filePath = this.getNodeParameter('filePath') as string;
const returnData: INodeExecutionData[] = [];
const length = items.length as unknown as number;
let item: INodeExecutionData;
let data;
try {
data = await fsReadFileAsync(filePath) as Buffer;
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error(`The file "${filePath}" could not be found.`);
for (let itemIndex = 0; itemIndex < length; itemIndex++) {
item = items[itemIndex];
const dataPropertyName = this.getNodeParameter('dataPropertyName', itemIndex) as string;
const filePath = this.getNodeParameter('filePath', itemIndex) as string;
let data;
try {
data = await fsReadFileAsync(filePath) as Buffer;
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error(`The file "${filePath}" could not be found.`);
}
throw error;
}
throw error;
}
const newItem: INodeExecutionData = {
json: item.json,
binary: {},
};
const newItem: INodeExecutionData = {
json: item.json,
binary: {},
};
if (item.binary !== undefined) {
// Create a shallow copy of the binary data so that the old
// data references which do not get changed still stay behind
// but the incoming data does not get changed.
Object.assign(newItem.binary, item.binary);
}
if (item.binary !== undefined) {
// Create a shallow copy of the binary data so that the old
// data references which do not get changed still stay behind
// but the incoming data does not get changed.
Object.assign(newItem.binary, item.binary);
}
newItem.binary![dataPropertyName] = await this.helpers.prepareBinaryData(data, filePath);
return newItem;
newItem.binary![dataPropertyName] = await this.helpers.prepareBinaryData(data, filePath);
returnData.push(newItem);
}
return this.prepareOutputData(returnData);
}
}

View file

@ -1,6 +1,6 @@
import {
BINARY_ENCODING,
IExecuteSingleFunctions,
IExecuteFunctions,
} from 'n8n-core';
import {
@ -37,22 +37,30 @@ export class ReadPdf implements INodeType {
],
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
async executeSingle(this: IExecuteSingleFunctions): Promise<INodeExecutionData> {
const returnData: INodeExecutionData[] = [];
const length = items.length as unknown as number;
let item: INodeExecutionData;
const binaryPropertyName = this.getNodeParameter('binaryPropertyName') as string;
for (let itemIndex = 0; itemIndex < length; itemIndex++) {
item = items[itemIndex];
const binaryPropertyName = this.getNodeParameter('binaryPropertyName', itemIndex) as string;
const item = this.getInputData();
if (item.binary === undefined) {
item.binary = {};
}
if (item.binary === undefined) {
item.binary = {};
const binaryData = Buffer.from(item.binary[binaryPropertyName].data, BINARY_ENCODING);
returnData.push({
binary: item.binary,
json: await pdf(binaryData),
});
}
const binaryData = Buffer.from(item.binary[binaryPropertyName].data, BINARY_ENCODING);
return {
binary: item.binary,
json: await pdf(binaryData),
};
return this.prepareOutputData(returnData);
}
}

View file

@ -1,6 +1,7 @@
import {
BINARY_ENCODING,
IExecuteSingleFunctions,
IExecuteFunctions,
IExecuteSingleFunctions
} from 'n8n-core';
import {
IDataObject,
@ -53,39 +54,53 @@ export class WriteBinaryFile implements INodeType {
};
async executeSingle(this: IExecuteSingleFunctions): Promise<INodeExecutionData> {
const item = this.getInputData();
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const dataPropertyName = this.getNodeParameter('dataPropertyName') as string;
const fileName = this.getNodeParameter('fileName') as string;
const returnData: INodeExecutionData[] = [];
const length = items.length as unknown as number;
let item: INodeExecutionData;
if (item.binary === undefined) {
throw new Error('No binary data set. So file can not be written!');
for (let itemIndex = 0; itemIndex < length; itemIndex++) {
const dataPropertyName = this.getNodeParameter('dataPropertyName', itemIndex) as string;
const fileName = this.getNodeParameter('fileName', itemIndex) as string;
item = items[itemIndex];
if (item.binary === undefined) {
throw new Error('No binary data set. So file can not be written!');
}
if (item.binary[dataPropertyName] === undefined) {
throw new Error(`The binary property "${dataPropertyName}" does not exist. So no file can be written!`);
}
// Write the file to disk
await fsWriteFileAsync(fileName, Buffer.from(item.binary[dataPropertyName].data, BINARY_ENCODING), 'binary');
const newItem: INodeExecutionData = {
json: {},
};
Object.assign(newItem.json, item.json);
if (item.binary !== undefined) {
// Create a shallow copy of the binary data so that the old
// data references which do not get changed still stay behind
// but the incoming data does not get changed.
newItem.binary = {};
Object.assign(newItem.binary, item.binary);
}
// Add the file name to data
(newItem.json as IDataObject).fileName = fileName;
returnData.push(newItem);
}
if (item.binary[dataPropertyName] === undefined) {
throw new Error(`The binary property "${dataPropertyName}" does not exist. So no file can be written!`);
}
// Write the file to disk
await fsWriteFileAsync(fileName, Buffer.from(item.binary[dataPropertyName].data, BINARY_ENCODING), 'binary');
const newItem: INodeExecutionData = {
json: {},
};
Object.assign(newItem.json, item.json);
if (item.binary !== undefined) {
// Create a shallow copy of the binary data so that the old
// data references which do not get changed still stay behind
// but the incoming data does not get changed.
newItem.binary = {};
Object.assign(newItem.binary, item.binary);
}
// Add the file name to data
(newItem.json as IDataObject).fileName = fileName;
return newItem;
return this.prepareOutputData(returnData);
}
}