This commit is contained in:
Dana 2025-03-05 17:06:38 +01:00 committed by GitHub
commit ed643ee40a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 262 additions and 3 deletions

View file

@ -157,6 +157,32 @@
<a id='redirectUrl' href='{{redirectUrl}}' style='display: none;'></a>
{{/if}}
<script>
document.addEventListener('DOMContentLoaded', function () {
const binary = "{{{responseBinary}}}" ? JSON.parse(decodeURIComponent("{{{responseBinary}}}")) : '';
console.log('dgl binary', binary);
if (binary) {
const decodedBinary = atob(binary.data);
console.log('dgl decodedBinary', decodedBinary);
const blob = new Blob([decodedBinary], {
fileExtension: binary.fileExtension ?? "",
fileName: binary.fileName ?? "",
type: binary.mimeType ?? "",
});
console.log('dgl blob', blob);
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = binary.fileName ?? "file";
document.body.appendChild(link);
console.log('dgl link', link);
link.click();
document.body.removeChild(link);
}
});
fetch('', {
method: 'POST',
body: {}

View file

@ -153,6 +153,11 @@ const completionProperties = updateDisplayOptions(
value: 'showText',
description: 'Display simple text or HTML',
},
{
name: 'Return Binary File',
value: 'returnBinary',
description: 'Return incoming binary file',
},
],
},
{
@ -176,7 +181,7 @@ const completionProperties = updateDisplayOptions(
required: true,
displayOptions: {
show: {
respondWith: ['text'],
respondWith: ['text', 'returnBinary'],
},
},
},
@ -190,7 +195,7 @@ const completionProperties = updateDisplayOptions(
},
displayOptions: {
show: {
respondWith: ['text'],
respondWith: ['text', 'returnBinary'],
},
},
},
@ -210,6 +215,21 @@ const completionProperties = updateDisplayOptions(
placeholder: 'e.g. Thanks for filling the form',
description: 'The text to display on the page. Use HTML to show a customized web page.',
},
{
displayName: 'Input Data Field Name',
name: 'inputDataFieldName',
type: 'string',
displayOptions: {
show: {
respondWith: ['returnBinary'],
},
},
default: 'data',
placeholder: 'e.g. data',
description:
'Find the name of input field containing the binary data to return in the Input panel on the left, in the Binary tab',
hint: 'The name of the input field containing the binary file data to be returned',
},
...waitTimeProperties,
{
displayName: 'Options',
@ -233,7 +253,7 @@ const completionProperties = updateDisplayOptions(
],
displayOptions: {
show: {
respondWith: ['text'],
respondWith: ['text', 'returnBinary'],
},
},
},

View file

@ -3,10 +3,33 @@ import {
type NodeTypeAndVersion,
type IWebhookFunctions,
type IWebhookResponseData,
type IBinaryData,
type IDataObject,
OperationalError,
} from 'n8n-workflow';
import { sanitizeCustomCss, sanitizeHtml } from './utils';
const getBinaryDataFromNode = (context: IWebhookFunctions, nodeName: string): IDataObject => {
return context.evaluateExpression(`{{ $('${nodeName}').first().binary }}`) as IDataObject;
};
export const binaryResponse = (context: IWebhookFunctions): IDataObject => {
const inputDataFieldName = context.getNodeParameter('inputDataFieldName', '') as string;
const parentNodes = context.getParentNodes(context.getNode().name);
const binaryNode = parentNodes.find((node) =>
getBinaryDataFromNode(context, node?.name)?.hasOwnProperty(inputDataFieldName),
);
if (!binaryNode) {
throw new OperationalError(`No binary data with field ${inputDataFieldName} found.`);
}
const binaryData = getBinaryDataFromNode(context, binaryNode?.name)[
inputDataFieldName
] as IBinaryData;
return binaryData;
};
export const renderFormCompletion = async (
context: IWebhookFunctions,
res: Response,
@ -20,6 +43,8 @@ export const renderFormCompletion = async (
customCss?: string;
};
const responseText = context.getNodeParameter('responseText', '') as string;
const binary =
context.getNodeParameter('respondWith', '') === 'returnBinary' ? binaryResponse(context) : '';
let title = options.formTitle;
if (!title) {
@ -35,6 +60,7 @@ export const renderFormCompletion = async (
formTitle: title,
appendAttribution,
responseText: sanitizeHtml(responseText),
responseBinary: encodeURIComponent(JSON.stringify(binary)),
dangerousCustomCss: sanitizeCustomCss(options.customCss),
redirectUrl,
});

View file

@ -232,6 +232,7 @@ describe('Form Node', () => {
message: 'Test Message',
redirectUrl: '',
title: 'Test Title',
responseBinary: '%22%22',
responseText: '',
},
},
@ -246,6 +247,7 @@ describe('Form Node', () => {
redirectUrl: '',
title: 'Test Title',
responseText: '<div>hey</div>',
responseBinary: '%22%22',
},
},
{
@ -257,6 +259,7 @@ describe('Form Node', () => {
formTitle: 'test',
message: 'Test Message',
redirectUrl: '',
responseBinary: '%22%22',
title: 'Test Title',
responseText: 'my text over here',
},
@ -434,6 +437,7 @@ describe('Form Node', () => {
redirectUrl: 'https://n8n.io',
responseText: '',
title: 'Test Title',
responseBinary: '%22%22',
});
});
});

View file

@ -0,0 +1,183 @@
import { type Response } from 'express';
import { type MockProxy, mock } from 'jest-mock-extended';
import { type INode, type IWebhookFunctions } from 'n8n-workflow';
import { renderFormCompletion } from '../formCompletionUtils';
describe('formCompletionUtils', () => {
let mockWebhookFunctions: MockProxy<IWebhookFunctions>;
const mockNode: INode = mock<INode>({
id: 'test-node',
name: 'Test Node',
type: 'test',
typeVersion: 1,
position: [0, 0],
parameters: {},
});
const expectedBinaryResponse = {
inputData: {
data: 'IyAxLiBHbyBpbiBwb3N0Z3',
fileExtension: 'txt',
fileName: 'file.txt',
fileSize: '458 B',
fileType: 'text',
mimeType: 'text/plain',
},
};
beforeEach(() => {
mockWebhookFunctions = mock<IWebhookFunctions>();
mockWebhookFunctions.getNode.mockReturnValue(mockNode);
});
afterEach(() => {
jest.resetAllMocks();
});
describe('renderFormCompletion', () => {
const mockResponse: Response = mock<Response>({
send: jest.fn(),
render: jest.fn(),
});
const trigger = {
name: 'triggerNode',
type: 'trigger',
typeVersion: 1,
disabled: false,
};
afterEach(() => {
jest.resetAllMocks();
});
it('should render the form completion', async () => {
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
completionTitle: 'Form Completion',
completionMessage: 'Form has been submitted successfully',
options: { formTitle: 'Form Title' },
};
return params[parameterName];
});
await renderFormCompletion(mockWebhookFunctions, mockResponse, trigger);
expect(mockResponse.render).toHaveBeenCalledWith('form-trigger-completion', {
appendAttribution: undefined,
formTitle: 'Form Title',
message: 'Form has been submitted successfully',
redirectUrl: undefined,
responseBinary: encodeURIComponent(JSON.stringify('')),
responseText: '',
title: 'Form Completion',
});
});
it('throw an error if no binary data with the field name is found', async () => {
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
completionTitle: 'Form Completion',
completionMessage: 'Form has been submitted successfully',
options: { formTitle: 'Form Title' },
respondWith: 'returnBinary',
inputDataFieldName: 'inputData',
};
return params[parameterName];
});
mockWebhookFunctions.getParentNodes.mockReturnValueOnce([]);
await expect(
renderFormCompletion(mockWebhookFunctions, mockResponse, trigger),
).rejects.toThrowError('No binary data with field inputData found.');
});
it('should render if respond with binary is set', async () => {
const nodeNameWithFileToDownload = 'prevNode0';
const nodeNameWithFile = 'prevNode2';
const parentNodesWithAndWithoutFiles = [
{
name: nodeNameWithFileToDownload,
type: '',
typeVersion: 0,
disabled: false,
},
{
name: 'prevNode1',
type: '',
typeVersion: 0,
disabled: false,
},
];
const parentNodesWithMultipleBinaryFiles = [
{
name: nodeNameWithFileToDownload,
type: '',
typeVersion: 0,
disabled: false,
},
{
name: nodeNameWithFile,
type: '',
typeVersion: 0,
disabled: false,
},
];
const parentNodesWithSingleNodeFile = [
{
name: nodeNameWithFileToDownload,
type: '',
typeVersion: 0,
disabled: false,
},
];
const parentNodesTestCases = [
parentNodesWithAndWithoutFiles,
parentNodesWithMultipleBinaryFiles,
parentNodesWithSingleNodeFile,
];
for (const parentNodes of parentNodesTestCases) {
mockWebhookFunctions.getParentNodes.mockReturnValueOnce(parentNodes);
mockWebhookFunctions.evaluateExpression.mockImplementation((arg) => {
if (arg === `{{ $('${nodeNameWithFileToDownload}').first().binary }}`) {
return expectedBinaryResponse;
} else if (arg === `{{ $('${nodeNameWithFile}').first().binary }}`) {
return { someData: {} };
} else {
return undefined;
}
});
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
inputDataFieldName: 'inputData',
completionTitle: 'Form Completion',
completionMessage: 'Form has been submitted successfully',
options: { formTitle: 'Form Title' },
respondWith: 'returnBinary',
};
return params[parameterName];
});
await renderFormCompletion(mockWebhookFunctions, mockResponse, trigger);
expect(mockResponse.render).toHaveBeenCalledWith('form-trigger-completion', {
appendAttribution: undefined,
formTitle: 'Form Title',
message: 'Form has been submitted successfully',
redirectUrl: undefined,
responseBinary: encodeURIComponent(JSON.stringify(expectedBinaryResponse.inputData)),
responseText: '',
title: 'Form Completion',
});
}
});
});
});