first commit
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled

This commit is contained in:
2026-03-17 16:22:57 +03:30
commit 3d5eaf9445
15349 changed files with 2847338 additions and 0 deletions
@@ -0,0 +1,39 @@
{
"node": "n8n-nodes-base.switch",
"nodeVersion": "1.0",
"codexVersion": "1.0",
"categories": ["Core Nodes"],
"resources": {
"primaryDocumentation": [
{
"url": "https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.switch/"
}
],
"generic": [
{
"label": "2021: The Year to Automate the New You with n8n",
"icon": "☀️",
"url": "https://n8n.io/blog/2021-the-year-to-automate-the-new-you-with-n8n/"
},
{
"label": "How to get started with CRM automation (with 3 no-code workflow ideas",
"icon": "👥",
"url": "https://n8n.io/blog/how-to-get-started-with-crm-automation-and-no-code-workflow-ideas/"
},
{
"label": "Build your own virtual assistant with n8n: A step by step guide",
"icon": "👦",
"url": "https://n8n.io/blog/build-your-own-virtual-assistant-with-n8n-a-step-by-step-guide/"
},
{
"label": "How to automatically manage contributions to open-source projects",
"icon": "🏷️",
"url": "https://n8n.io/blog/automation-for-maintainers-of-open-source-projects/"
}
]
},
"alias": ["Router", "If", "Path", "Filter", "Condition", "Logic", "Branch", "Case"],
"subcategories": {
"Core Nodes": ["Flow"]
}
}
@@ -0,0 +1,32 @@
import type { INodeTypeBaseDescription, IVersionedNodeType } from 'n8n-workflow';
import { VersionedNodeType } from 'n8n-workflow';
import { SwitchV1 } from './V1/SwitchV1.node';
import { SwitchV2 } from './V2/SwitchV2.node';
import { SwitchV3 } from './V3/SwitchV3.node';
export class Switch extends VersionedNodeType {
constructor() {
const baseDescription: INodeTypeBaseDescription = {
displayName: 'Switch',
name: 'switch',
icon: 'fa:map-signs',
iconColor: 'light-blue',
group: ['transform'],
description: 'Route items depending on defined expression or rules',
defaultVersion: 3.4,
};
const nodeVersions: IVersionedNodeType['nodeVersions'] = {
1: new SwitchV1(baseDescription),
2: new SwitchV2(baseDescription),
3: new SwitchV3(baseDescription),
3.1: new SwitchV3(baseDescription),
3.2: new SwitchV3(baseDescription),
3.3: new SwitchV3(baseDescription),
3.4: new SwitchV3(baseDescription),
};
super(nodeVersions, baseDescription);
}
}
@@ -0,0 +1,691 @@
import type {
IExecuteFunctions,
INodeExecutionData,
INodeParameters,
INodeType,
INodeTypeBaseDescription,
INodeTypeDescription,
NodeParameterValue,
} from 'n8n-workflow';
import { NodeConnectionTypes, NodeOperationError } from 'n8n-workflow';
export class SwitchV1 implements INodeType {
description: INodeTypeDescription;
constructor(baseDescription: INodeTypeBaseDescription) {
this.description = {
...baseDescription,
version: [1],
defaults: {
name: 'Switch',
color: '#506000',
},
inputs: [NodeConnectionTypes.Main],
outputs: [
NodeConnectionTypes.Main,
NodeConnectionTypes.Main,
NodeConnectionTypes.Main,
NodeConnectionTypes.Main,
],
outputNames: ['0', '1', '2', '3'],
properties: [
{
displayName: 'Mode',
name: 'mode',
type: 'options',
options: [
{
name: 'Expression',
value: 'expression',
description: 'Expression decides how to route data',
},
{
name: 'Rules',
value: 'rules',
description: 'Rules decide how to route data',
},
],
default: 'rules',
description: 'How data should be routed',
},
// ----------------------------------
// mode:expression
// ----------------------------------
{
displayName: 'Output',
name: 'output',
type: 'number',
typeOptions: {
minValue: 0,
maxValue: 3,
},
displayOptions: {
show: {
mode: ['expression'],
},
},
default: 0,
description: 'The index of output to which to send data to',
},
// ----------------------------------
// mode:rules
// ----------------------------------
{
displayName: 'Data Type',
name: 'dataType',
type: 'options',
displayOptions: {
show: {
mode: ['rules'],
},
},
options: [
{
name: 'Boolean',
value: 'boolean',
},
{
name: 'Date & Time',
value: 'dateTime',
},
{
name: 'Number',
value: 'number',
},
{
name: 'String',
value: 'string',
},
],
default: 'number',
description: 'The type of data to route on',
},
// ----------------------------------
// dataType:boolean
// ----------------------------------
{
displayName: 'Value 1',
name: 'value1',
type: 'boolean',
displayOptions: {
show: {
dataType: ['boolean'],
mode: ['rules'],
},
},
default: false,
// eslint-disable-next-line n8n-nodes-base/node-param-description-boolean-without-whether
description: 'The value to compare with the first one',
},
{
displayName: 'Routing Rules',
name: 'rules',
placeholder: 'Add Routing Rule',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
displayOptions: {
show: {
dataType: ['boolean'],
mode: ['rules'],
},
},
default: {},
options: [
{
name: 'rules',
displayName: 'Boolean',
values: [
// eslint-disable-next-line n8n-nodes-base/node-param-operation-without-no-data-expression
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Equal',
value: 'equal',
},
{
name: 'Not Equal',
value: 'notEqual',
},
],
default: 'equal',
description: 'Operation to decide where the data should be mapped to',
},
{
displayName: 'Value 2',
name: 'value2',
type: 'boolean',
default: false,
// eslint-disable-next-line n8n-nodes-base/node-param-description-boolean-without-whether
description: 'The value to compare with the first one',
},
{
displayName: 'Output',
name: 'output',
type: 'number',
typeOptions: {
minValue: 0,
maxValue: 3,
},
default: 0,
description: 'The index of output to which to send data to if rule matches',
},
],
},
],
},
// ----------------------------------
// dataType:dateTime
// ----------------------------------
{
displayName: 'Value 1',
name: 'value1',
type: 'dateTime',
displayOptions: {
show: {
dataType: ['dateTime'],
mode: ['rules'],
},
},
default: '',
description: 'The value to compare with the second one',
},
{
displayName: 'Routing Rules',
name: 'rules',
placeholder: 'Add Routing Rule',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
displayOptions: {
show: {
dataType: ['dateTime'],
mode: ['rules'],
},
},
default: {},
options: [
{
name: 'rules',
displayName: 'Dates',
values: [
// eslint-disable-next-line n8n-nodes-base/node-param-operation-without-no-data-expression
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Occurred After',
value: 'after',
},
{
name: 'Occurred Before',
value: 'before',
},
],
default: 'after',
description: 'Operation to decide where the data should be mapped to',
},
{
displayName: 'Value 2',
name: 'value2',
type: 'dateTime',
default: 0,
description: 'The value to compare with the first one',
},
{
displayName: 'Output',
name: 'output',
type: 'number',
typeOptions: {
minValue: 0,
maxValue: 3,
},
default: 0,
description: 'The index of output to which to send data to if rule matches',
},
],
},
],
},
// ----------------------------------
// dataType:number
// ----------------------------------
{
displayName: 'Value 1',
name: 'value1',
type: 'number',
displayOptions: {
show: {
dataType: ['number'],
mode: ['rules'],
},
},
default: 0,
description: 'The value to compare with the second one',
},
{
displayName: 'Routing Rules',
name: 'rules',
placeholder: 'Add Routing Rule',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
displayOptions: {
show: {
dataType: ['number'],
mode: ['rules'],
},
},
default: {},
options: [
{
name: 'rules',
displayName: 'Numbers',
values: [
// eslint-disable-next-line n8n-nodes-base/node-param-operation-without-no-data-expression
{
displayName: 'Operation',
name: 'operation',
type: 'options',
// eslint-disable-next-line n8n-nodes-base/node-param-options-type-unsorted-items
options: [
{
name: 'Smaller',
value: 'smaller',
},
{
name: 'Smaller Equal',
value: 'smallerEqual',
},
{
name: 'Equal',
value: 'equal',
},
{
name: 'Not Equal',
value: 'notEqual',
},
{
name: 'Larger',
value: 'larger',
},
{
name: 'Larger Equal',
value: 'largerEqual',
},
],
default: 'smaller',
description: 'Operation to decide where the data should be mapped to',
},
{
displayName: 'Value 2',
name: 'value2',
type: 'number',
default: 0,
description: 'The value to compare with the first one',
},
{
displayName: 'Output',
name: 'output',
type: 'number',
typeOptions: {
minValue: 0,
maxValue: 3,
},
default: 0,
description: 'The index of output to which to send data to if rule matches',
},
],
},
],
},
// ----------------------------------
// dataType:string
// ----------------------------------
{
displayName: 'Value 1',
name: 'value1',
type: 'string',
displayOptions: {
show: {
dataType: ['string'],
mode: ['rules'],
},
},
default: '',
description: 'The value to compare with the second one',
},
{
displayName: 'Routing Rules',
name: 'rules',
placeholder: 'Add Routing Rule',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
displayOptions: {
show: {
dataType: ['string'],
mode: ['rules'],
},
},
default: {},
options: [
{
name: 'rules',
displayName: 'Strings',
values: [
// eslint-disable-next-line n8n-nodes-base/node-param-operation-without-no-data-expression
{
displayName: 'Operation',
name: 'operation',
type: 'options',
// eslint-disable-next-line n8n-nodes-base/node-param-options-type-unsorted-items
options: [
{
name: 'Contains',
value: 'contains',
},
{
name: 'Not Contains',
value: 'notContains',
},
{
name: 'Ends With',
value: 'endsWith',
},
{
name: 'Not Ends With',
value: 'notEndsWith',
},
{
name: 'Equal',
value: 'equal',
},
{
name: 'Not Equal',
value: 'notEqual',
},
{
name: 'Regex Match',
value: 'regex',
},
{
name: 'Regex Not Match',
value: 'notRegex',
},
{
name: 'Starts With',
value: 'startsWith',
},
{
name: 'Not Starts With',
value: 'notStartsWith',
},
],
default: 'equal',
description: 'Operation to decide where the data should be mapped to',
},
{
displayName: 'Value 2',
name: 'value2',
type: 'string',
displayOptions: {
hide: {
operation: ['regex', 'notRegex'],
},
},
default: '',
description: 'The value to compare with the first one',
},
{
displayName: 'Regex',
name: 'value2',
type: 'string',
displayOptions: {
show: {
operation: ['regex', 'notRegex'],
},
},
default: '',
placeholder: '/text/i',
description: 'The regex which has to match',
},
{
displayName: 'Output',
name: 'output',
type: 'number',
typeOptions: {
minValue: 0,
maxValue: 3,
},
default: 0,
description: 'The index of output to which to send data to if rule matches',
},
],
},
],
},
{
displayName: 'Fallback Output',
name: 'fallbackOutput',
type: 'options',
displayOptions: {
show: {
mode: ['rules'],
},
},
// eslint-disable-next-line n8n-nodes-base/node-param-options-type-unsorted-items
options: [
{
name: 'None',
value: -1,
},
{
name: '0',
value: 0,
},
{
name: '1',
value: 1,
},
{
name: '2',
value: 2,
},
{
name: '3',
value: 3,
},
],
default: -1,
description: 'The output to which to route all items which do not match any of the rules',
},
],
};
}
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const returnData: INodeExecutionData[][] = [[], [], [], []];
const items = this.getInputData();
let compareOperationResult: boolean;
let item: INodeExecutionData;
let mode: string;
let outputIndex: number;
let ruleData: INodeParameters;
// The compare operations
const compareOperationFunctions: {
[key: string]: (value1: NodeParameterValue, value2: NodeParameterValue) => boolean;
} = {
after: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) > (value2 || 0),
before: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) < (value2 || 0),
contains: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || '').toString().includes((value2 || '').toString()),
notContains: (value1: NodeParameterValue, value2: NodeParameterValue) =>
!(value1 || '').toString().includes((value2 || '').toString()),
endsWith: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 as string).endsWith(value2 as string),
notEndsWith: (value1: NodeParameterValue, value2: NodeParameterValue) =>
!(value1 as string).endsWith(value2 as string),
equal: (value1: NodeParameterValue, value2: NodeParameterValue) => value1 === value2,
notEqual: (value1: NodeParameterValue, value2: NodeParameterValue) => value1 !== value2,
larger: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) > (value2 || 0),
largerEqual: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) >= (value2 || 0),
smaller: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) < (value2 || 0),
smallerEqual: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) <= (value2 || 0),
startsWith: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 as string).startsWith(value2 as string),
notStartsWith: (value1: NodeParameterValue, value2: NodeParameterValue) =>
!(value1 as string).startsWith(value2 as string),
regex: (value1: NodeParameterValue, value2: NodeParameterValue) => {
const regexMatch = (value2 || '').toString().match(new RegExp('^/(.*?)/([gimusy]*)$'));
let regex: RegExp;
if (!regexMatch) {
regex = new RegExp((value2 || '').toString());
} else if (regexMatch.length === 1) {
regex = new RegExp(regexMatch[1]);
} else {
regex = new RegExp(regexMatch[1], regexMatch[2]);
}
return !!(value1 || '').toString().match(regex);
},
notRegex: (value1: NodeParameterValue, value2: NodeParameterValue) => {
const regexMatch = (value2 || '').toString().match(new RegExp('^/(.*?)/([gimusy]*)$'));
let regex: RegExp;
if (!regexMatch) {
regex = new RegExp((value2 || '').toString());
} else if (regexMatch.length === 1) {
regex = new RegExp(regexMatch[1]);
} else {
regex = new RegExp(regexMatch[1], regexMatch[2]);
}
return !(value1 || '').toString().match(regex);
},
};
// Converts the input data of a dateTime into a number for easy compare
const convertDateTime = (value: NodeParameterValue): number => {
let returnValue: number | undefined = undefined;
if (typeof value === 'string') {
returnValue = new Date(value).getTime();
} else if (typeof value === 'number') {
returnValue = value;
}
if ((value as unknown as object) instanceof Date) {
returnValue = (value as unknown as Date).getTime();
}
if (returnValue === undefined || isNaN(returnValue)) {
throw new NodeOperationError(
this.getNode(),
`The value "${value}" is not a valid DateTime.`,
);
}
return returnValue;
};
const checkIndexRange = (index: number) => {
if (index < 0 || index >= returnData.length) {
throw new NodeOperationError(
this.getNode(),
`The ouput ${index} is not allowed. It has to be between 0 and ${returnData.length - 1}!`,
);
}
};
// Iterate over all items to check to which output they should be routed to
itemLoop: for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
try {
item = items[itemIndex];
mode = this.getNodeParameter('mode', itemIndex) as string;
if (mode === 'expression') {
// One expression decides how to route item
outputIndex = this.getNodeParameter('output', itemIndex) as number;
checkIndexRange(outputIndex);
returnData[outputIndex].push(item);
} else if (mode === 'rules') {
// Rules decide how to route item
const dataType = this.getNodeParameter('dataType', 0) as string;
let value1 = this.getNodeParameter('value1', itemIndex) as NodeParameterValue;
if (dataType === 'dateTime') {
value1 = convertDateTime(value1);
}
for (ruleData of this.getNodeParameter(
'rules.rules',
itemIndex,
[],
) as INodeParameters[]) {
// Check if the values passes
let value2 = ruleData.value2 as NodeParameterValue;
if (dataType === 'dateTime') {
value2 = convertDateTime(value2);
}
compareOperationResult = compareOperationFunctions[ruleData.operation as string](
value1,
value2,
);
if (compareOperationResult) {
// If rule matches add it to the correct output and continue with next item
checkIndexRange(ruleData.output as number);
returnData[ruleData.output as number].push(item);
continue itemLoop;
}
}
// Check if a fallback output got defined and route accordingly
outputIndex = this.getNodeParameter('fallbackOutput', itemIndex) as number;
if (outputIndex !== -1) {
checkIndexRange(outputIndex);
returnData[outputIndex].push(item);
}
}
} catch (error) {
if (this.continueOnFail()) {
returnData[0].push({ json: { error: error.message } });
continue;
}
throw error;
}
}
return returnData;
}
}
@@ -0,0 +1,225 @@
{
"name": "review node unit tests",
"nodes": [
{
"parameters": {},
"id": "fb04a728-d2b9-4b98-8d3b-3762b0a60c43",
"name": "When clicking \"Execute Workflow\"",
"type": "n8n-nodes-base.manualTrigger",
"typeVersion": 1,
"position": [
-7020,
1700
]
},
{
"parameters": {
"mode": "expression",
"output": "={{ $json.data }}"
},
"id": "6addcb47-5a9d-4a02-a915-b3b60b2ffad3",
"name": "Switch",
"type": "n8n-nodes-base.switch",
"typeVersion": 1,
"position": [
-6460,
1700
]
},
{
"parameters": {
"values": {
"number": [
{
"name": "data[0]"
},
{
"name": "data[1]",
"value": 1
},
{
"name": "data[2]",
"value": 2
},
{
"name": "data[3]",
"value": 3
}
]
},
"options": {}
},
"id": "b1f9468e-4604-48ff-a851-4041b224f9a5",
"name": "Set",
"type": "n8n-nodes-base.set",
"typeVersion": 1,
"position": [
-6840,
1700
]
},
{
"parameters": {},
"id": "66650986-03a4-4cd7-a7c9-3792218cb2f5",
"name": "Output 0",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [
-6180,
1460
]
},
{
"parameters": {
"fieldToSplitOut": "data",
"options": {}
},
"id": "808579aa-9da2-4c6b-bdd6-387119593d97",
"name": "Item Lists",
"type": "n8n-nodes-base.itemLists",
"typeVersion": 1,
"position": [
-6660,
1700
]
},
{
"parameters": {},
"id": "dd764387-3ff7-4a6c-8451-3a0511f80415",
"name": "Output 1",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [
-6180,
1620
]
},
{
"parameters": {},
"id": "02561ebf-8054-4d12-98b1-e099bcb20b34",
"name": "Output 2",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [
-6180,
1780
]
},
{
"parameters": {},
"id": "bfaaacd7-956c-4e6f-bc40-f6459bc43faa",
"name": "Output 3",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [
-6180,
1940
]
}
],
"pinData": {
"Output 0": [
{
"json": {
"data": 0
}
}
],
"Output 1": [
{
"json": {
"data": 1
}
}
],
"Output 2": [
{
"json": {
"data": 2
}
}
],
"Output 3": [
{
"json": {
"data": 3
}
}
]
},
"connections": {
"When clicking \"Execute Workflow\"": {
"main": [
[
{
"node": "Set",
"type": "main",
"index": 0
}
]
]
},
"Switch": {
"main": [
[
{
"node": "Output 0",
"type": "main",
"index": 0
}
],
[
{
"node": "Output 1",
"type": "main",
"index": 0
}
],
[
{
"node": "Output 2",
"type": "main",
"index": 0
}
],
[
{
"node": "Output 3",
"type": "main",
"index": 0
}
]
]
},
"Set": {
"main": [
[
{
"node": "Item Lists",
"type": "main",
"index": 0
}
]
]
},
"Item Lists": {
"main": [
[
{
"node": "Switch",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {},
"versionId": "d9f4d9b1-a282-473e-a527-f1e6c3b5bb89",
"id": "182",
"meta": {
"instanceId": "104a4d08d8897b8bdeb38aaca515021075e0bd8544c983c2bb8c86e6a8e6081c"
},
"tags": []
}
@@ -0,0 +1,5 @@
import { NodeTestHarness } from '@nodes-testing/node-test-harness';
describe('Execute Switch Node', () => {
new NodeTestHarness().setupTests();
});
@@ -0,0 +1,242 @@
{
"name": "review node unit tests",
"nodes": [
{
"parameters": {},
"id": "ec017d65-ca3c-4df3-ba84-e79da16c05b3",
"name": "When clicking \"Execute Workflow\"",
"type": "n8n-nodes-base.manualTrigger",
"typeVersion": 1,
"position": [
-8460,
1740
]
},
{
"parameters": {
"values": {
"number": [
{
"name": "data[0]"
},
{
"name": "data[1]",
"value": 1
},
{
"name": "data[2]",
"value": 2
},
{
"name": "data[3]",
"value": 3
}
]
},
"options": {}
},
"id": "1a799394-e0a8-459f-b9a6-0b656e315df6",
"name": "Set",
"type": "n8n-nodes-base.set",
"typeVersion": 1,
"position": [
-8280,
1740
]
},
{
"parameters": {},
"id": "56138ddd-b0b7-429e-b740-37da602fd250",
"name": "Output 0",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [
-7640,
1500
]
},
{
"parameters": {
"fieldToSplitOut": "data",
"options": {}
},
"id": "a2af4a95-866c-44ac-9a58-0eb94fe6a27a",
"name": "Item Lists",
"type": "n8n-nodes-base.itemLists",
"typeVersion": 1,
"position": [
-8100,
1740
]
},
{
"parameters": {},
"id": "55dd8064-5ed1-49ab-9c9a-5de8266b0c87",
"name": "Output 1",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [
-7640,
1660
]
},
{
"parameters": {},
"id": "605a11b1-6fe2-48cc-944f-0f8d89cff669",
"name": "Output 2",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [
-7640,
1820
]
},
{
"parameters": {},
"id": "6615c351-46ba-4013-b49b-9f44f5195a2e",
"name": "Output 3",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [
-7640,
1980
]
},
{
"parameters": {
"value1": "={{ $json.data }}",
"rules": {
"rules": [
{
"operation": "equal"
},
{
"operation": "equal",
"value2": 1,
"output": 1
},
{
"operation": "equal",
"value2": 2,
"output": 2
}
]
},
"fallbackOutput": 3
},
"id": "176e3656-28fb-45b9-9ac5-385c4c544d9e",
"name": "Switch",
"type": "n8n-nodes-base.switch",
"typeVersion": 1,
"position": [
-7900,
1740
]
}
],
"pinData": {
"Output 0": [
{
"json": {
"data": 0
}
}
],
"Output 1": [
{
"json": {
"data": 1
}
}
],
"Output 2": [
{
"json": {
"data": 2
}
}
],
"Output 3": [
{
"json": {
"data": 3
}
}
]
},
"connections": {
"When clicking \"Execute Workflow\"": {
"main": [
[
{
"node": "Set",
"type": "main",
"index": 0
}
]
]
},
"Set": {
"main": [
[
{
"node": "Item Lists",
"type": "main",
"index": 0
}
]
]
},
"Item Lists": {
"main": [
[
{
"node": "Switch",
"type": "main",
"index": 0
}
]
]
},
"Switch": {
"main": [
[
{
"node": "Output 0",
"type": "main",
"index": 0
}
],
[
{
"node": "Output 1",
"type": "main",
"index": 0
}
],
[
{
"node": "Output 2",
"type": "main",
"index": 0
}
],
[
{
"node": "Output 3",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {},
"versionId": "962a14d7-c5a6-4e29-96f3-6208877d3d45",
"id": "182",
"meta": {
"instanceId": "104a4d08d8897b8bdeb38aaca515021075e0bd8544c983c2bb8c86e6a8e6081c"
},
"tags": []
}
@@ -0,0 +1,712 @@
import type {
IExecuteFunctions,
ILoadOptionsFunctions,
INodeExecutionData,
INodeParameters,
INodePropertyOptions,
INodeType,
INodeTypeBaseDescription,
INodeTypeDescription,
NodeParameterValue,
} from 'n8n-workflow';
import { NodeConnectionTypes, NodeOperationError } from 'n8n-workflow';
export class SwitchV2 implements INodeType {
description: INodeTypeDescription;
constructor(baseDescription: INodeTypeBaseDescription) {
this.description = {
...baseDescription,
version: [2],
defaults: {
name: 'Switch',
color: '#506000',
},
inputs: [NodeConnectionTypes.Main],
outputs: `={{
((parameters) => {
const rules = parameters.rules?.rules ?? [];
const mode = parameters.mode;
if (mode === 'expression') {
return Array
.from(
{ length: parameters.outputsAmount },
(_, i) => ({ type: "${NodeConnectionTypes.Main}", displayName: i.toString() })
)
}
return rules.map(value => {
return { type: "${NodeConnectionTypes.Main}", displayName: value.outputKey }
})
})($parameter)
}}`,
properties: [
{
displayName: 'Mode',
name: 'mode',
type: 'options',
options: [
{
name: 'Expression',
value: 'expression',
description: 'Expression decides how to route data',
},
{
name: 'Rules',
value: 'rules',
description: 'Rules decide how to route data',
},
],
default: 'rules',
description: 'How data should be routed',
},
// ----------------------------------
// mode:expression
// ----------------------------------
{
displayName: 'Output',
name: 'output',
type: 'string',
displayOptions: {
show: {
mode: ['expression'],
},
},
default: '',
description: 'The index of output to which to send data to',
},
{
displayName: 'Outputs Amount',
name: 'outputsAmount',
type: 'number',
displayOptions: {
show: {
mode: ['expression'],
},
},
default: 4,
description: 'Amount of outputs to create',
},
// ----------------------------------
// mode:rules
// ----------------------------------
{
displayName: 'Data Type',
name: 'dataType',
type: 'options',
displayOptions: {
show: {
mode: ['rules'],
},
},
options: [
{
name: 'Boolean',
value: 'boolean',
},
{
name: 'Date & Time',
value: 'dateTime',
},
{
name: 'Number',
value: 'number',
},
{
name: 'String',
value: 'string',
},
],
default: 'number',
description: 'The type of data to route on',
},
// ----------------------------------
// dataType:boolean
// ----------------------------------
{
displayName: 'Value 1',
name: 'value1',
type: 'boolean',
displayOptions: {
show: {
dataType: ['boolean'],
mode: ['rules'],
},
},
default: false,
// eslint-disable-next-line n8n-nodes-base/node-param-description-boolean-without-whether
description: 'The value to compare with the first one',
},
{
displayName: 'Routing Rules',
name: 'rules',
placeholder: 'Add Routing Rule',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
sortable: true,
},
displayOptions: {
show: {
dataType: ['boolean'],
mode: ['rules'],
},
},
default: {},
options: [
{
name: 'rules',
displayName: 'Boolean',
values: [
// eslint-disable-next-line n8n-nodes-base/node-param-operation-without-no-data-expression
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Equal',
value: 'equal',
},
{
name: 'Not Equal',
value: 'notEqual',
},
],
default: 'equal',
description: 'Operation to decide where the data should be mapped to',
},
{
displayName: 'Value 2',
name: 'value2',
type: 'boolean',
default: false,
// eslint-disable-next-line n8n-nodes-base/node-param-description-boolean-without-whether
description: 'The value to compare with the first one',
},
{
displayName: 'Output Key',
name: 'outputKey',
type: 'string',
default: '',
description: 'The label of output to which to send data to if rule matches',
},
],
},
],
},
// ----------------------------------
// dataType:dateTime
// ----------------------------------
{
displayName: 'Value 1',
name: 'value1',
type: 'dateTime',
displayOptions: {
show: {
dataType: ['dateTime'],
mode: ['rules'],
},
},
default: '',
description: 'The value to compare with the second one',
},
{
displayName: 'Routing Rules',
name: 'rules',
placeholder: 'Add Routing Rule',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
sortable: true,
},
displayOptions: {
show: {
dataType: ['dateTime'],
mode: ['rules'],
},
},
default: {},
options: [
{
name: 'rules',
displayName: 'Dates',
values: [
// eslint-disable-next-line n8n-nodes-base/node-param-operation-without-no-data-expression
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Occurred After',
value: 'after',
},
{
name: 'Occurred Before',
value: 'before',
},
],
default: 'after',
description: 'Operation to decide where the data should be mapped to',
},
{
displayName: 'Value 2',
name: 'value2',
type: 'dateTime',
default: 0,
description: 'The value to compare with the first one',
},
{
displayName: 'Output Key',
name: 'outputKey',
type: 'string',
default: '',
description: 'The label of output to which to send data to if rule matches',
},
],
},
],
},
// ----------------------------------
// dataType:number
// ----------------------------------
{
displayName: 'Value 1',
name: 'value1',
type: 'number',
displayOptions: {
show: {
dataType: ['number'],
mode: ['rules'],
},
},
default: 0,
description: 'The value to compare with the second one',
},
{
displayName: 'Routing Rules',
name: 'rules',
placeholder: 'Add Routing Rule',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
sortable: true,
},
displayOptions: {
show: {
dataType: ['number'],
mode: ['rules'],
},
},
default: {},
options: [
{
name: 'rules',
displayName: 'Numbers',
values: [
// eslint-disable-next-line n8n-nodes-base/node-param-operation-without-no-data-expression
{
displayName: 'Operation',
name: 'operation',
type: 'options',
// eslint-disable-next-line n8n-nodes-base/node-param-options-type-unsorted-items
options: [
{
name: 'Smaller',
value: 'smaller',
},
{
name: 'Smaller Equal',
value: 'smallerEqual',
},
{
name: 'Equal',
value: 'equal',
},
{
name: 'Not Equal',
value: 'notEqual',
},
{
name: 'Larger',
value: 'larger',
},
{
name: 'Larger Equal',
value: 'largerEqual',
},
],
default: 'smaller',
description: 'Operation to decide where the data should be mapped to',
},
{
displayName: 'Value 2',
name: 'value2',
type: 'number',
default: 0,
description: 'The value to compare with the first one',
},
{
displayName: 'Output Key',
name: 'outputKey',
type: 'string',
default: '',
description: 'The label of output to which to send data to if rule matches',
},
],
},
],
},
// ----------------------------------
// dataType:string
// ----------------------------------
{
displayName: 'Value 1',
name: 'value1',
type: 'string',
displayOptions: {
show: {
dataType: ['string'],
mode: ['rules'],
},
},
default: '',
description: 'The value to compare with the second one',
},
{
displayName: 'Routing Rules',
name: 'rules',
placeholder: 'Add Routing Rule',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
sortable: true,
},
displayOptions: {
show: {
dataType: ['string'],
mode: ['rules'],
},
},
default: {},
options: [
{
name: 'rules',
displayName: 'Strings',
values: [
// eslint-disable-next-line n8n-nodes-base/node-param-operation-without-no-data-expression
{
displayName: 'Operation',
name: 'operation',
type: 'options',
// eslint-disable-next-line n8n-nodes-base/node-param-options-type-unsorted-items
options: [
{
name: 'Contains',
value: 'contains',
},
{
name: 'Not Contains',
value: 'notContains',
},
{
name: 'Ends With',
value: 'endsWith',
},
{
name: 'Not Ends With',
value: 'notEndsWith',
},
{
name: 'Equal',
value: 'equal',
},
{
name: 'Not Equal',
value: 'notEqual',
},
{
name: 'Regex Match',
value: 'regex',
},
{
name: 'Regex Not Match',
value: 'notRegex',
},
{
name: 'Starts With',
value: 'startsWith',
},
{
name: 'Not Starts With',
value: 'notStartsWith',
},
],
default: 'equal',
description: 'Operation to decide where the data should be mapped to',
},
{
displayName: 'Value 2',
name: 'value2',
type: 'string',
displayOptions: {
hide: {
operation: ['regex', 'notRegex'],
},
},
default: '',
description: 'The value to compare with the first one',
},
{
displayName: 'Regex',
name: 'value2',
type: 'string',
displayOptions: {
show: {
operation: ['regex', 'notRegex'],
},
},
default: '',
placeholder: '/text/i',
description: 'The regex which has to match',
},
{
displayName: 'Output Key',
name: 'outputKey',
type: 'string',
default: '',
description: 'The label of output to which to send data to if rule matches',
},
],
},
],
},
{
displayName: 'Fallback Output Name or ID',
name: 'fallbackOutput',
type: 'options',
displayOptions: {
show: {
mode: ['rules'],
},
},
typeOptions: {
loadOptionsDependsOn: ['rules.rules'],
loadOptionsMethod: 'getFallbackOutputOptions',
},
default: -1,
description:
'The output to which to route all items which do not match any of the rules. Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code/expressions/">expression</a>.',
},
],
};
}
methods = {
loadOptions: {
async getFallbackOutputOptions(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const rules = (this.getCurrentNodeParameter('rules.rules') as INodeParameters[]) ?? [];
const options = rules.map((rule, index) => ({
name: `${index} ${rule.outputKey as string}`,
value: index,
}));
options.unshift({
name: 'None',
value: -1,
});
return options;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
let returnData: INodeExecutionData[][] = [];
const items = this.getInputData();
let compareOperationResult: boolean;
let item: INodeExecutionData;
let mode: string;
let outputIndex: number;
let ruleData: INodeParameters;
// The compare operations
const compareOperationFunctions: {
[key: string]: (value1: NodeParameterValue, value2: NodeParameterValue) => boolean;
} = {
after: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) > (value2 || 0),
before: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) < (value2 || 0),
contains: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || '').toString().includes((value2 || '').toString()),
notContains: (value1: NodeParameterValue, value2: NodeParameterValue) =>
!(value1 || '').toString().includes((value2 || '').toString()),
endsWith: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 as string).endsWith(value2 as string),
notEndsWith: (value1: NodeParameterValue, value2: NodeParameterValue) =>
!(value1 as string).endsWith(value2 as string),
equal: (value1: NodeParameterValue, value2: NodeParameterValue) => value1 === value2,
notEqual: (value1: NodeParameterValue, value2: NodeParameterValue) => value1 !== value2,
larger: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) > (value2 || 0),
largerEqual: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) >= (value2 || 0),
smaller: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) < (value2 || 0),
smallerEqual: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 || 0) <= (value2 || 0),
startsWith: (value1: NodeParameterValue, value2: NodeParameterValue) =>
(value1 as string).startsWith(value2 as string),
notStartsWith: (value1: NodeParameterValue, value2: NodeParameterValue) =>
!(value1 as string).startsWith(value2 as string),
regex: (value1: NodeParameterValue, value2: NodeParameterValue) => {
const regexMatch = (value2 || '').toString().match(new RegExp('^/(.*?)/([gimusy]*)$'));
let regex: RegExp;
if (!regexMatch) {
regex = new RegExp((value2 || '').toString());
} else if (regexMatch.length === 1) {
regex = new RegExp(regexMatch[1]);
} else {
regex = new RegExp(regexMatch[1], regexMatch[2]);
}
return !!(value1 || '').toString().match(regex);
},
notRegex: (value1: NodeParameterValue, value2: NodeParameterValue) => {
const regexMatch = (value2 || '').toString().match(new RegExp('^/(.*?)/([gimusy]*)$'));
let regex: RegExp;
if (!regexMatch) {
regex = new RegExp((value2 || '').toString());
} else if (regexMatch.length === 1) {
regex = new RegExp(regexMatch[1]);
} else {
regex = new RegExp(regexMatch[1], regexMatch[2]);
}
return !(value1 || '').toString().match(regex);
},
};
// Converts the input data of a dateTime into a number for easy compare
const convertDateTime = (value: NodeParameterValue): number => {
let returnValue: number | undefined = undefined;
if (typeof value === 'string') {
returnValue = new Date(value).getTime();
} else if (typeof value === 'number') {
returnValue = value;
}
if ((value as unknown as object) instanceof Date) {
returnValue = (value as unknown as Date).getTime();
}
if (returnValue === undefined || isNaN(returnValue)) {
throw new NodeOperationError(
this.getNode(),
`The value "${value}" is not a valid DateTime.`,
);
}
return returnValue;
};
const checkIndexRange = (index: number) => {
if (index < 0 || index >= returnData.length) {
throw new NodeOperationError(
this.getNode(),
`The ouput ${index} is not allowed. It has to be between 0 and ${returnData.length - 1}!`,
);
}
};
// Iterate over all items to check to which output they should be routed to
itemLoop: for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
try {
item = items[itemIndex];
const rules = this.getNodeParameter('rules.rules', itemIndex, []) as INodeParameters[];
mode = this.getNodeParameter('mode', itemIndex) as string;
item.pairedItem = { item: itemIndex };
if (mode === 'expression') {
const outputsAmount = this.getNodeParameter('outputsAmount', itemIndex) as number;
if (itemIndex === 0) {
returnData = new Array(outputsAmount).fill(0).map(() => []);
}
// One expression decides how to route item
outputIndex = this.getNodeParameter('output', itemIndex) as number;
checkIndexRange(outputIndex);
returnData[outputIndex].push(item);
} else if (mode === 'rules') {
// Rules decide how to route item
if (itemIndex === 0) {
returnData = new Array(rules.length).fill(0).map(() => []);
}
const dataType = this.getNodeParameter('dataType', 0) as string;
let value1 = this.getNodeParameter('value1', itemIndex) as NodeParameterValue;
if (dataType === 'dateTime') {
value1 = convertDateTime(value1);
}
for (ruleData of rules) {
// Check if the values passes
let value2 = ruleData.value2 as NodeParameterValue;
if (dataType === 'dateTime') {
value2 = convertDateTime(value2);
}
compareOperationResult = compareOperationFunctions[ruleData.operation as string](
value1,
value2,
);
if (compareOperationResult) {
// If rule matches add it to the correct output and continue with next item
checkIndexRange(ruleData.output as number);
const ruleIndex = rules.indexOf(ruleData);
returnData[ruleIndex].push(item);
continue itemLoop;
}
}
// Check if a fallback output got defined and route accordingly
outputIndex = this.getNodeParameter('fallbackOutput', itemIndex) as number;
if (outputIndex !== -1) {
checkIndexRange(outputIndex);
returnData[outputIndex].push(item);
}
}
} catch (error) {
if (this.continueOnFail()) {
returnData[0].push({ json: { error: error.message } });
continue;
}
throw error;
}
}
return returnData;
}
}
@@ -0,0 +1,167 @@
{
"name": "My workflow 109",
"nodes": [
{
"parameters": {},
"id": "7ae16f96-5c2c-44a3-9f96-167e426336f9",
"name": "When clicking \"Execute Workflow\"",
"type": "n8n-nodes-base.manualTrigger",
"typeVersion": 1,
"position": [620, 720]
},
{
"parameters": {
"data": [
{
"output": "third",
"text": "third output text"
},
{
"output": "fourth",
"text": "fourth output text"
},
{
"output": "first",
"text": "first output text"
},
{
"output": "second",
"text": "second output text"
}
]
},
"id": "31e9aada-7aa2-4c62-8e15-0cecb91788e4",
"name": "Code",
"type": "n8n-nodes-testing.testData",
"typeVersion": 1,
"position": [840, 720]
},
{
"parameters": {},
"id": "cf10b4c7-16a6-4c16-a17c-7b83f954f7b9",
"name": "No Operation, do nothing",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1380, 560]
},
{
"parameters": {},
"id": "3e7e7f4a-bff9-4ce1-a5e5-58505853260f",
"name": "No Operation, do nothing1",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1380, 720]
},
{
"parameters": {},
"id": "205f59d6-52f5-4412-9511-b680a91d0be2",
"name": "No Operation, do nothing2",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1380, 880]
},
{
"parameters": {
"mode": "expression",
"output": "={{ Math.max(0, ['first', 'second', 'third'].indexOf( $json.output)) }}",
"outputsAmount": 3
},
"id": "9c3dc163-0103-45c2-8455-e6ab3e84679c",
"name": "Switch1",
"type": "n8n-nodes-base.switch",
"typeVersion": 2,
"position": [1100, 720]
}
],
"pinData": {
"No Operation, do nothing2": [
{
"json": {
"output": "third",
"text": "third output text"
}
}
],
"No Operation, do nothing1": [
{
"json": {
"output": "second",
"text": "second output text"
}
}
],
"No Operation, do nothing": [
{
"json": {
"output": "fourth",
"text": "fourth output text"
}
},
{
"json": {
"output": "first",
"text": "first output text"
}
}
]
},
"connections": {
"When clicking \"Execute Workflow\"": {
"main": [
[
{
"node": "Code",
"type": "main",
"index": 0
}
]
]
},
"Code": {
"main": [
[
{
"node": "Switch1",
"type": "main",
"index": 0
}
]
]
},
"Switch1": {
"main": [
[
{
"node": "No Operation, do nothing",
"type": "main",
"index": 0
}
],
[
{
"node": "No Operation, do nothing1",
"type": "main",
"index": 0
}
],
[
{
"node": "No Operation, do nothing2",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {
"executionOrder": "v1"
},
"versionId": "cca0f0b9-d01e-435b-9125-9616007f4aea",
"id": "xjPY8ZYJK53G6nQ1",
"meta": {
"instanceId": "ec7a5f4ffdb34436e59d23eaccb5015b5238de2a877e205b28572bf1ffecfe04"
},
"tags": []
}
@@ -0,0 +1,5 @@
import { NodeTestHarness } from '@nodes-testing/node-test-harness';
describe('Execute Switch Node', () => {
new NodeTestHarness().setupTests();
});
@@ -0,0 +1,183 @@
{
"name": "My workflow 109",
"nodes": [
{
"parameters": {},
"id": "7ae16f96-5c2c-44a3-9f96-167e426336f9",
"name": "When clicking \"Execute Workflow\"",
"type": "n8n-nodes-base.manualTrigger",
"typeVersion": 1,
"position": [620, 720]
},
{
"parameters": {
"data": [
{
"output": "third",
"text": "third output text"
},
{
"output": "fourth",
"text": "fourth output text"
},
{
"output": "first",
"text": "first output text"
},
{
"output": "second",
"text": "second output text"
}
]
},
"id": "31e9aada-7aa2-4c62-8e15-0cecb91788e4",
"name": "Code",
"type": "n8n-nodes-testing.testData",
"typeVersion": 1,
"position": [840, 720]
},
{
"parameters": {
"dataType": "string",
"value1": "={{ $json.output }}",
"rules": {
"rules": [
{
"value2": "first",
"outputKey": "First Output"
},
{
"value2": "second",
"outputKey": "Second Output"
},
{
"value2": "third",
"outputKey": "Third Output"
}
]
},
"fallbackOutput": 2
},
"id": "0dd6e98a-2830-42fb-9a9d-6d4ff8678cbd",
"name": "Switch",
"type": "n8n-nodes-base.switch",
"typeVersion": 2,
"position": [1120, 720]
},
{
"parameters": {},
"id": "cf10b4c7-16a6-4c16-a17c-7b83f954f7b9",
"name": "No Operation, do nothing",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1380, 560]
},
{
"parameters": {},
"id": "3e7e7f4a-bff9-4ce1-a5e5-58505853260f",
"name": "No Operation, do nothing1",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1380, 720]
},
{
"parameters": {},
"id": "205f59d6-52f5-4412-9511-b680a91d0be2",
"name": "No Operation, do nothing2",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1380, 880]
}
],
"pinData": {
"No Operation, do nothing": [
{
"json": {
"output": "first",
"text": "first output text"
}
}
],
"No Operation, do nothing1": [
{
"json": {
"output": "second",
"text": "second output text"
}
}
],
"No Operation, do nothing2": [
{
"json": {
"output": "third",
"text": "third output text"
}
},
{
"json": {
"output": "fourth",
"text": "fourth output text"
}
}
]
},
"connections": {
"When clicking \"Execute Workflow\"": {
"main": [
[
{
"node": "Code",
"type": "main",
"index": 0
}
]
]
},
"Code": {
"main": [
[
{
"node": "Switch",
"type": "main",
"index": 0
}
]
]
},
"Switch": {
"main": [
[
{
"node": "No Operation, do nothing",
"type": "main",
"index": 0
}
],
[
{
"node": "No Operation, do nothing1",
"type": "main",
"index": 0
}
],
[
{
"node": "No Operation, do nothing2",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {
"executionOrder": "v1"
},
"versionId": "627af20f-47fc-47a7-8da6-a7e7b21225df",
"id": "xjPY8ZYJK53G6nQ1",
"meta": {
"instanceId": "ec7a5f4ffdb34436e59d23eaccb5015b5238de2a877e205b28572bf1ffecfe04"
},
"tags": []
}
@@ -0,0 +1,440 @@
import set from 'lodash/set';
import type {
IDataObject,
IExecuteFunctions,
ILoadOptionsFunctions,
INodeExecutionData,
INodeParameters,
INodePropertyOptions,
INodeType,
INodeTypeBaseDescription,
INodeTypeDescription,
} from 'n8n-workflow';
import { ApplicationError, NodeConnectionTypes, NodeOperationError } from 'n8n-workflow';
import { capitalize } from '@utils/utilities';
import { ENABLE_LESS_STRICT_TYPE_VALIDATION } from '../../../utils/constants';
import { looseTypeValidationProperty } from '../../../utils/descriptions';
import { getTypeValidationParameter, getTypeValidationStrictness } from '../../If/V2/utils';
const configuredOutputs = (parameters: INodeParameters) => {
const mode = parameters.mode as string;
if (mode === 'expression') {
return Array.from({ length: parameters.numberOutputs as number }, (_, i) => ({
type: 'main',
displayName: i.toString(),
}));
} else {
const rules = ((parameters.rules as IDataObject)?.values as IDataObject[]) ?? [];
const ruleOutputs = rules.map((rule, index) => {
return {
type: 'main',
displayName: rule.outputKey || index.toString(),
};
});
if ((parameters.options as IDataObject)?.fallbackOutput === 'extra') {
const renameFallbackOutput = (parameters.options as IDataObject)?.renameFallbackOutput;
ruleOutputs.push({
type: 'main',
displayName: renameFallbackOutput || 'Fallback',
});
}
return ruleOutputs;
}
};
export class SwitchV3 implements INodeType {
description: INodeTypeDescription;
constructor(baseDescription: INodeTypeBaseDescription) {
this.description = {
...baseDescription,
subtitle: `=mode: {{(${capitalize})($parameter["mode"])}}`,
version: [3, 3.1, 3.2, 3.3, 3.4],
defaults: {
name: 'Switch',
color: '#506000',
},
inputs: [NodeConnectionTypes.Main],
outputs: `={{(${configuredOutputs})($parameter)}}`,
properties: [
{
displayName: 'Mode',
name: 'mode',
type: 'options',
noDataExpression: true,
options: [
{
name: 'Rules',
value: 'rules',
description: 'Build a matching rule for each output',
},
{
name: 'Expression',
value: 'expression',
description: 'Write an expression to return the output index',
},
],
default: 'rules',
description: 'How data should be routed',
},
{
displayName: 'Number of Outputs',
name: 'numberOutputs',
type: 'number',
noDataExpression: true,
displayOptions: {
show: {
mode: ['expression'],
'@version': [{ _cnd: { gte: 3.3 } }],
},
},
default: 4,
description: 'How many outputs to create',
},
{
displayName: 'Number of Outputs',
name: 'numberOutputs',
type: 'number',
displayOptions: {
show: {
mode: ['expression'],
'@version': [{ _cnd: { lt: 3.3 } }],
},
},
default: 4,
description: 'How many outputs to create',
},
{
displayName: 'Output Index',
name: 'output',
type: 'number',
validateType: 'number',
hint: 'The index to route the item to, starts at 0',
displayOptions: {
show: {
mode: ['expression'],
},
},
// eslint-disable-next-line n8n-nodes-base/node-param-default-wrong-for-number
default: '={{}}',
description:
'The output index to send the input item to. Use an expression to calculate which input item should be routed to which output. The expression must return a number.',
},
{
displayName: 'Routing Rules',
name: 'rules',
placeholder: 'Add Routing Rule',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
sortable: true,
},
default: {
values: [
{
conditions: {
options: {
caseSensitive: true,
leftValue: '',
typeValidation: 'strict',
},
conditions: [
{
leftValue: '',
rightValue: '',
operator: {
type: 'string',
operation: 'equals',
},
},
],
combinator: 'and',
},
},
],
},
displayOptions: {
show: {
mode: ['rules'],
},
},
options: [
{
name: 'values',
displayName: 'Routing Rule',
values: [
{
displayName: 'Conditions',
name: 'conditions',
placeholder: 'Add Condition',
type: 'filter',
default: {},
typeOptions: {
multipleValues: false,
filter: {
caseSensitive: '={{!$parameter.options.ignoreCase}}',
typeValidation: getTypeValidationStrictness(3.1),
version: '={{ $nodeVersion >=3.4 ? 3 : $nodeVersion >= 3.2 ? 2 : 1 }}',
},
},
},
{
displayName: 'Rename Output',
name: 'renameOutput',
type: 'boolean',
default: false,
},
{
displayName: 'Output Name',
name: 'outputKey',
type: 'string',
default: '',
description: 'The label of output to which to send data to if rule matches',
displayOptions: {
show: {
renameOutput: [true],
},
},
},
],
},
],
},
{
...looseTypeValidationProperty,
default: false,
displayOptions: {
show: {
'@version': [{ _cnd: { gte: 3.1 } }],
},
},
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add option',
default: {},
displayOptions: {
show: {
mode: ['rules'],
},
},
options: [
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-wrong-for-dynamic-options
displayName: 'Fallback Output',
name: 'fallbackOutput',
type: 'options',
typeOptions: {
loadOptionsDependsOn: ['rules.values', '/rules', '/rules.values'],
loadOptionsMethod: 'getFallbackOutputOptions',
},
default: 'none',
// eslint-disable-next-line n8n-nodes-base/node-param-description-wrong-for-dynamic-options
description:
'If no rule matches the item will be sent to this output, by default they will be ignored',
},
{
displayName: 'Ignore Case',
description: 'Whether to ignore letter case when evaluating conditions',
name: 'ignoreCase',
type: 'boolean',
default: true,
},
{
...looseTypeValidationProperty,
displayOptions: {
show: {
'@version': [{ _cnd: { lt: 3.1 } }],
},
},
},
{
displayName: 'Rename Fallback Output',
name: 'renameFallbackOutput',
type: 'string',
placeholder: 'e.g. Fallback',
default: '',
displayOptions: {
show: {
fallbackOutput: ['extra'],
},
},
},
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
displayName: 'Send data to all matching outputs',
name: 'allMatchingOutputs',
type: 'boolean',
default: false,
description:
'Whether to send data to all outputs meeting conditions (and not just the first one)',
},
],
},
],
};
}
methods = {
loadOptions: {
async getFallbackOutputOptions(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const rules = (this.getCurrentNodeParameter('rules.values') as INodeParameters[]) ?? [];
const outputOptions: INodePropertyOptions[] = [
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'None (default)',
value: 'none',
description: 'Items will be ignored',
},
{
name: 'Extra Output',
value: 'extra',
description: 'Items will be sent to the extra, separate, output',
},
];
for (const [index, rule] of rules.entries()) {
outputOptions.push({
name: `Output ${rule.outputKey || index}`,
value: index,
description: `Items will be sent to the same output as when matched rule ${index + 1}`,
});
}
return outputOptions;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
let returnData: INodeExecutionData[][] = [];
const items = this.getInputData();
const mode = this.getNodeParameter('mode', 0) as string;
const checkIndexRange = (returnDataLength: number, index: number, itemIndex = 0) => {
if (Number(index) === returnDataLength) {
throw new NodeOperationError(this.getNode(), `The ouput ${index} is not allowed. `, {
itemIndex,
description: `Output indexes are zero based, if you want to use the extra output use ${
index - 1
}`,
});
}
if (index < 0 || index > returnDataLength) {
throw new NodeOperationError(this.getNode(), `The ouput ${index} is not allowed`, {
itemIndex,
description: `It has to be between 0 and ${returnDataLength - 1}`,
});
}
};
itemLoop: for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
try {
const item = items[itemIndex];
item.pairedItem = { item: itemIndex };
if (mode === 'expression') {
const numberOutputs = this.getNodeParameter('numberOutputs', itemIndex) as number;
if (itemIndex === 0) {
returnData = new Array(numberOutputs).fill(0).map(() => []);
}
const outputIndex = this.getNodeParameter('output', itemIndex) as number;
checkIndexRange(returnData.length, outputIndex, itemIndex);
returnData[outputIndex].push(item);
} else if (mode === 'rules') {
const rules = this.getNodeParameter('rules.values', itemIndex, []) as INodeParameters[];
if (!rules.length) continue;
const options = this.getNodeParameter('options', itemIndex, {});
const fallbackOutput = options.fallbackOutput;
if (itemIndex === 0) {
returnData = new Array(rules.length).fill(0).map(() => []);
if (fallbackOutput === 'extra') {
returnData.push([]);
}
}
let matchFound = false;
for (const [ruleIndex, rule] of rules.entries()) {
let conditionPass;
try {
conditionPass = this.getNodeParameter(
`rules.values[${ruleIndex}].conditions`,
itemIndex,
false,
{
extractValue: true,
},
) as boolean;
} catch (error) {
if (
!getTypeValidationParameter(3.1)(
this,
itemIndex,
options.looseTypeValidation as boolean,
) &&
!error.description
) {
error.description = ENABLE_LESS_STRICT_TYPE_VALIDATION;
}
set(error, 'context.itemIndex', itemIndex);
set(error, 'node', this.getNode());
throw error;
}
if (conditionPass) {
matchFound = true;
checkIndexRange(returnData.length, rule.output as number, itemIndex);
returnData[ruleIndex].push(item);
if (!options.allMatchingOutputs) {
continue itemLoop;
}
}
}
if (fallbackOutput !== undefined && fallbackOutput !== 'none' && !matchFound) {
if (fallbackOutput === 'extra') {
returnData[returnData.length - 1].push(item);
continue;
}
checkIndexRange(returnData.length, fallbackOutput as number, itemIndex);
returnData[fallbackOutput as number].push(item);
}
}
} catch (error) {
if (this.continueOnFail()) {
returnData[0].push({ json: { error: error.message } });
continue;
}
if (error instanceof NodeOperationError) {
throw error;
}
if (error instanceof ApplicationError) {
set(error, 'context.itemIndex', itemIndex);
throw error;
}
throw new NodeOperationError(this.getNode(), error, {
itemIndex,
});
}
}
if (!returnData.length) return [[]];
return returnData;
}
}
@@ -0,0 +1,167 @@
{
"name": "My workflow 64",
"nodes": [
{
"parameters": {},
"id": "58cc2d21-a8b1-424d-a8e4-e79d39955fa8",
"name": "When clicking \"Execute Workflow\"",
"type": "n8n-nodes-base.manualTrigger",
"typeVersion": 1,
"position": [0, 620]
},
{
"parameters": {
"data": [
{
"output": "third",
"text": "third output text"
},
{
"output": "fourth",
"text": "fourth output text"
},
{
"output": "first",
"text": "first output text"
},
{
"output": "second",
"text": "second output text"
}
]
},
"id": "85adf7fc-2d33-49aa-b4bb-2000cce07ce0",
"name": "Code",
"type": "n8n-nodes-testing.testData",
"typeVersion": 1,
"position": [220, 620]
},
{
"parameters": {},
"id": "ebab0b65-6feb-416c-828e-ca5e766ea048",
"name": "No Operation, do nothing",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [760, 460]
},
{
"parameters": {},
"id": "2f58a703-b7ae-4279-a60b-a0243af3b563",
"name": "No Operation, do nothing1",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [760, 620]
},
{
"parameters": {},
"id": "b1d0b310-6edf-4a40-a66d-689078ddbf31",
"name": "No Operation, do nothing2",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [760, 780]
},
{
"parameters": {
"mode": "expression",
"numberOutputs": 3,
"output": "={{ Math.max(0, ['first', 'second', 'third'].indexOf( $json.output)) }}"
},
"id": "437e2c46-81d8-4c76-a036-db767576f55d",
"name": "Switch",
"type": "n8n-nodes-base.switch",
"typeVersion": 3,
"position": [460, 620]
}
],
"pinData": {
"No Operation, do nothing2": [
{
"json": {
"output": "third",
"text": "third output text"
}
}
],
"No Operation, do nothing1": [
{
"json": {
"output": "second",
"text": "second output text"
}
}
],
"No Operation, do nothing": [
{
"json": {
"output": "fourth",
"text": "fourth output text"
}
},
{
"json": {
"output": "first",
"text": "first output text"
}
}
]
},
"connections": {
"When clicking \"Execute Workflow\"": {
"main": [
[
{
"node": "Code",
"type": "main",
"index": 0
}
]
]
},
"Code": {
"main": [
[
{
"node": "Switch",
"type": "main",
"index": 0
}
]
]
},
"Switch": {
"main": [
[
{
"node": "No Operation, do nothing",
"type": "main",
"index": 0
}
],
[
{
"node": "No Operation, do nothing1",
"type": "main",
"index": 0
}
],
[
{
"node": "No Operation, do nothing2",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {
"executionOrder": "v1"
},
"versionId": "c72f2f9b-5089-42c2-8939-b70d9467a718",
"id": "1vDZkJN9SpYXu0Ic",
"meta": {
"instanceId": "b888bd11cd1ddbb95450babf3e199556799d999b896f650de768b8370ee50363"
},
"tags": []
}
@@ -0,0 +1,570 @@
import { mockDeep } from 'jest-mock-extended';
import type {
IExecuteFunctions,
ILoadOptionsFunctions,
INodeTypeBaseDescription,
} from 'n8n-workflow';
import { NodeOperationError, ApplicationError } from 'n8n-workflow';
import { SwitchV3 } from '../SwitchV3.node';
describe('SwitchV3 Node', () => {
let switchNode: SwitchV3;
let mockExecuteFunctions: jest.Mocked<IExecuteFunctions>;
let mockLoadOptionsFunctions: jest.Mocked<ILoadOptionsFunctions>;
const baseDescription: INodeTypeBaseDescription = {
displayName: 'Switch',
name: 'n8n-nodes-base.switch',
group: ['transform'],
description: 'Route items to different outputs',
};
beforeEach(() => {
switchNode = new SwitchV3(baseDescription);
mockExecuteFunctions = mockDeep<IExecuteFunctions>();
mockLoadOptionsFunctions = mockDeep<ILoadOptionsFunctions>();
jest.clearAllMocks();
});
describe('Version-specific behavior', () => {
it('should have two numberOutputs parameters with different version conditions', () => {
const switchNode = new SwitchV3(baseDescription);
const numberOutputsParams = switchNode.description.properties.filter(
(prop) => prop.name === 'numberOutputs',
);
expect(numberOutputsParams).toHaveLength(2);
});
it('should have noDataExpression: true for version 3.3+ numberOutputs parameter', () => {
const switchNode = new SwitchV3(baseDescription);
const numberOutputsParamWithNoExpression = switchNode.description.properties.find(
(prop) => prop.name === 'numberOutputs' && prop.noDataExpression === true,
);
expect(numberOutputsParamWithNoExpression).toBeDefined();
expect(numberOutputsParamWithNoExpression?.noDataExpression).toBe(true);
expect(numberOutputsParamWithNoExpression?.displayOptions?.show?.['@version']).toEqual([
{ _cnd: { gte: 3.3 } },
]);
});
it('should have numberOutputs parameter without noDataExpression for older versions', () => {
const switchNode = new SwitchV3(baseDescription);
const numberOutputsParamWithoutNoExpression = switchNode.description.properties.find(
(prop) => prop.name === 'numberOutputs' && !prop.noDataExpression,
);
expect(numberOutputsParamWithoutNoExpression).toBeDefined();
expect(numberOutputsParamWithoutNoExpression?.noDataExpression).toBeUndefined();
expect(numberOutputsParamWithoutNoExpression?.displayOptions?.show?.['@version']).toEqual([
{ _cnd: { lt: 3.3 } },
]);
});
it('should include version 3.3 in supported versions', () => {
const switchNode = new SwitchV3(baseDescription);
expect(switchNode.description.version).toContain(3.3);
});
});
describe('Expression Mode Execution', () => {
beforeEach(() => {
mockExecuteFunctions.getNode.mockReturnValue({
id: 'switch-node',
name: 'Switch',
type: 'n8n-nodes-base.switch',
typeVersion: 3.3,
position: [0, 0],
parameters: {},
});
});
it('should route items to correct output in expression mode', async () => {
const inputData = [{ json: { value: 1 } }, { json: { value: 2 } }, { json: { value: 3 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation(
(paramName: string, itemIndex: number) => {
const params: Record<string, any> = {
mode: 'expression',
numberOutputs: 3,
output: itemIndex % 3,
};
return params[paramName];
},
);
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result).toHaveLength(3);
expect(result[0]).toHaveLength(1);
expect(result[0][0].json).toEqual({ value: 1 });
expect(result[1]).toHaveLength(1);
expect(result[1][0].json).toEqual({ value: 2 });
expect(result[2]).toHaveLength(1);
expect(result[2][0].json).toEqual({ value: 3 });
});
it('should handle multiple items routed to same output', async () => {
const inputData = [{ json: { value: 1 } }, { json: { value: 2 } }, { json: { value: 3 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation((paramName: string) => {
const params: Record<string, any> = {
mode: 'expression',
numberOutputs: 2,
output: 0,
};
return params[paramName];
});
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result).toHaveLength(2);
expect(result[0]).toHaveLength(3);
expect(result[1]).toHaveLength(0);
});
it('should throw error for invalid output index', async () => {
const inputData = [{ json: { value: 1 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation((paramName: string) => {
const params: Record<string, any> = {
mode: 'expression',
numberOutputs: 2,
output: 5,
};
return params[paramName];
});
await expect(switchNode.execute.call(mockExecuteFunctions)).rejects.toThrow(
NodeOperationError,
);
});
it('should throw error for negative output index', async () => {
const inputData = [{ json: { value: 1 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation((paramName: string) => {
const params: Record<string, any> = {
mode: 'expression',
numberOutputs: 2,
output: -1,
};
return params[paramName];
});
await expect(switchNode.execute.call(mockExecuteFunctions)).rejects.toThrow(
NodeOperationError,
);
});
it('should handle empty input data', async () => {
mockExecuteFunctions.getInputData.mockReturnValue([]);
mockExecuteFunctions.getNodeParameter.mockReturnValue('expression');
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result).toEqual([[]]);
});
});
describe('Rules Mode Execution', () => {
beforeEach(() => {
mockExecuteFunctions.getNode.mockReturnValue({
id: 'switch-node',
name: 'Switch',
type: 'n8n-nodes-base.switch',
typeVersion: 3.3,
position: [0, 0],
parameters: {},
});
});
it('should route items based on matching rules', async () => {
const inputData = [
{ json: { status: 'active' } },
{ json: { status: 'inactive' } },
{ json: { status: 'pending' } },
];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation((paramName: string) => {
if (paramName === 'mode') return 'rules';
if (paramName === 'rules.values') {
return [
{
conditions: {
conditions: [
{
leftValue: '={{$json.status}}',
rightValue: 'active',
operator: { type: 'string', operation: 'equals' },
},
],
combinator: 'and',
},
},
{
conditions: {
conditions: [
{
leftValue: '={{$json.status}}',
rightValue: 'inactive',
operator: { type: 'string', operation: 'equals' },
},
],
combinator: 'and',
},
},
];
}
if (paramName === 'options') return {};
return false;
});
mockExecuteFunctions.getNodeParameter.mockImplementation(
(paramName: string, itemIndex: number, defaultValue: any, options?: any) => {
if (paramName === 'mode') return 'rules';
if (paramName === 'rules.values') {
return [
{ conditions: { conditions: [], combinator: 'and' } },
{ conditions: { conditions: [], combinator: 'and' } },
];
}
if (paramName === 'options') return {};
if (paramName.includes('conditions') && options?.extractValue) {
if (itemIndex === 0) return true; // active matches first rule
if (itemIndex === 1) return false; // inactive doesn't match first rule
return false;
}
return defaultValue;
},
);
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result).toHaveLength(2);
expect(result[0]).toHaveLength(1);
expect(result[0][0].json).toEqual({ status: 'active' });
expect(result[1]).toHaveLength(0);
});
it('should handle fallback output when no rules match', async () => {
const inputData = [{ json: { status: 'unknown' } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation(
(paramName: string, _itemIndex: number, defaultValue: any, options?: any) => {
if (paramName === 'mode') return 'rules';
if (paramName === 'rules.values') {
return [{ conditions: { conditions: [], combinator: 'and' } }];
}
if (paramName === 'options') return { fallbackOutput: 'extra' };
if (paramName.includes('conditions') && options?.extractValue) {
return false; // No rule matches
}
return defaultValue;
},
);
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result).toHaveLength(2); // One rule output + one fallback output
expect(result[0]).toHaveLength(0); // No matches for rule
expect(result[1]).toHaveLength(1); // Item goes to fallback
expect(result[1][0].json).toEqual({ status: 'unknown' });
});
it('should handle allMatchingOutputs option', async () => {
const inputData = [{ json: { value: 10 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation(
(paramName: string, _itemIndex: number, defaultValue: any, options?: any) => {
if (paramName === 'mode') return 'rules';
if (paramName === 'rules.values') {
return [
{ conditions: { conditions: [], combinator: 'and' } },
{ conditions: { conditions: [], combinator: 'and' } },
];
}
if (paramName === 'options') return { allMatchingOutputs: true };
if (paramName.includes('conditions') && options?.extractValue) {
return true; // Both rules match
}
return defaultValue;
},
);
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result).toHaveLength(2);
expect(result[0]).toHaveLength(1);
expect(result[1]).toHaveLength(1);
expect(result[0][0].json).toEqual({ value: 10 });
expect(result[1][0].json).toEqual({ value: 10 });
});
it('should skip items when no rules are defined', async () => {
const inputData = [{ json: { value: 1 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation((paramName: string) => {
if (paramName === 'mode') return 'rules';
if (paramName === 'rules.values') return [];
if (paramName === 'options') return {};
return undefined;
});
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result).toEqual([[]]);
});
});
describe('Error Handling', () => {
beforeEach(() => {
mockExecuteFunctions.getNode.mockReturnValue({
id: 'switch-node',
name: 'Switch',
type: 'n8n-nodes-base.switch',
typeVersion: 3.3,
position: [0, 0],
parameters: {},
});
});
it('should handle errors with continueOnFail', async () => {
const inputData = [{ json: { value: 1 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation((paramName: string) => {
if (paramName === 'mode') return 'expression';
if (paramName === 'numberOutputs') return 1;
if (paramName === 'output') {
throw new Error('Parameter error');
}
return undefined;
});
mockExecuteFunctions.continueOnFail.mockReturnValue(true);
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result[0][0].json).toHaveProperty('error', 'Parameter error');
});
it('should rethrow NodeOperationError', async () => {
const inputData = [{ json: { value: 1 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation(() => {
throw new NodeOperationError(mockExecuteFunctions.getNode(), 'Invalid parameter');
});
await expect(switchNode.execute.call(mockExecuteFunctions)).rejects.toThrow(
NodeOperationError,
);
});
it('should handle ApplicationError with context', async () => {
const inputData = [{ json: { value: 1 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation(() => {
const error = new ApplicationError('Application error');
throw error;
});
await expect(switchNode.execute.call(mockExecuteFunctions)).rejects.toThrow(ApplicationError);
});
it('should wrap generic errors in NodeOperationError', async () => {
const inputData = [{ json: { value: 1 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation((paramName: string) => {
if (paramName === 'mode') return 'expression';
if (paramName === 'numberOutputs') return 1;
if (paramName === 'output') {
throw new Error('Generic error');
}
return undefined;
});
await expect(switchNode.execute.call(mockExecuteFunctions)).rejects.toThrow(
NodeOperationError,
);
});
});
describe('Load Options', () => {
it('should load fallback output options with no rules', async () => {
mockLoadOptionsFunctions.getCurrentNodeParameter.mockReturnValue([]);
const result =
await switchNode.methods.loadOptions.getFallbackOutputOptions.call(
mockLoadOptionsFunctions,
);
expect(result).toEqual([
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'None (default)',
value: 'none',
description: 'Items will be ignored',
},
{
name: 'Extra Output',
value: 'extra',
description: 'Items will be sent to the extra, separate, output',
},
]);
});
it('should load fallback output options with rules', async () => {
const rules = [
{ outputKey: 'Rule 1' },
{ outputKey: 'Rule 2' },
{}, // Rule without outputKey
];
mockLoadOptionsFunctions.getCurrentNodeParameter.mockReturnValue(rules);
const result =
await switchNode.methods.loadOptions.getFallbackOutputOptions.call(
mockLoadOptionsFunctions,
);
expect(result).toEqual([
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'None (default)',
value: 'none',
description: 'Items will be ignored',
},
{
name: 'Extra Output',
value: 'extra',
description: 'Items will be sent to the extra, separate, output',
},
{
name: 'Output Rule 1',
value: 0,
description: 'Items will be sent to the same output as when matched rule 1',
},
{
name: 'Output Rule 2',
value: 1,
description: 'Items will be sent to the same output as when matched rule 2',
},
{
name: 'Output 2',
value: 2,
description: 'Items will be sent to the same output as when matched rule 3',
},
]);
});
it('should handle null rules parameter', async () => {
mockLoadOptionsFunctions.getCurrentNodeParameter.mockReturnValue(null);
const result =
await switchNode.methods.loadOptions.getFallbackOutputOptions.call(
mockLoadOptionsFunctions,
);
expect(result).toEqual([
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'None (default)',
value: 'none',
description: 'Items will be ignored',
},
{
name: 'Extra Output',
value: 'extra',
description: 'Items will be sent to the extra, separate, output',
},
]);
});
});
describe('Edge Cases', () => {
beforeEach(() => {
mockExecuteFunctions.getNode.mockReturnValue({
id: 'switch-node',
name: 'Switch',
type: 'n8n-nodes-base.switch',
typeVersion: 3.3,
position: [0, 0],
parameters: {},
});
});
it('should handle items with pairedItem already set', async () => {
const inputData = [{ json: { value: 1 }, pairedItem: { item: 5 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation((paramName: string) => {
const params: Record<string, any> = {
mode: 'expression',
numberOutputs: 1,
output: 0,
};
return params[paramName];
});
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result[0][0].pairedItem).toEqual({ item: 0 });
});
it('should handle output index equal to returnData length', async () => {
const inputData = [{ json: { value: 1 } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation((paramName: string) => {
const params: Record<string, any> = {
mode: 'expression',
numberOutputs: 2,
output: 2, // Equal to returnData length
};
return params[paramName];
});
await expect(switchNode.execute.call(mockExecuteFunctions)).rejects.toThrow(
NodeOperationError,
);
});
it('should handle fallback output to existing rule output', async () => {
const inputData = [{ json: { status: 'unknown' } }];
mockExecuteFunctions.getInputData.mockReturnValue(inputData);
mockExecuteFunctions.getNodeParameter.mockImplementation(
(paramName: string, _itemIndex: number, defaultValue: any, options?: any) => {
if (paramName === 'mode') return 'rules';
if (paramName === 'rules.values') {
return [{ conditions: { conditions: [], combinator: 'and' } }];
}
if (paramName === 'options') return { fallbackOutput: 0 };
if (paramName.includes('conditions') && options?.extractValue) {
return false; // No rule matches
}
return defaultValue;
},
);
const result = await switchNode.execute.call(mockExecuteFunctions);
expect(result).toHaveLength(1);
expect(result[0]).toHaveLength(1);
expect(result[0][0].json).toEqual({ status: 'unknown' });
});
});
});
@@ -0,0 +1,341 @@
{
"name": "Switch Regex Test",
"nodes": [
{
"parameters": {},
"id": "1301e15e-7a64-44bf-bc4b-d60e7b8c629a",
"name": "When clicking Execute workflow",
"type": "n8n-nodes-base.manualTrigger",
"typeVersion": 1,
"position": [780, 600]
},
{
"parameters": {},
"id": "be9a3cd8-7c19-493c-aacf-a52aba064324",
"name": "Fallback",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1680, 900]
},
{
"parameters": {},
"id": "f7de5522-5750-4102-9b3b-0a01f7bbf6cc",
"name": "Output",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1640, 320]
},
{
"parameters": {
"fields": {
"values": [
{
"name": "test",
"stringValue": "value"
}
]
},
"options": {}
},
"id": "55af4400-ed88-4ee2-b654-3a82bd112875",
"name": "Edit Fields",
"type": "n8n-nodes-base.set",
"typeVersion": 3.2,
"position": [1020, 600]
},
{
"parameters": {
"rules": {
"values": [
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "17eb6574-9578-4915-8365-772e08d2f06b",
"leftValue": "={{ $json.test }}",
"rightValue": "/^value$/g",
"operator": {
"type": "string",
"operation": "notRegex"
}
}
],
"combinator": "and"
}
}
]
},
"options": {
"fallbackOutput": "extra"
}
},
"id": "06657954-6bcb-4d60-a659-5d3e5e3d093d",
"name": "NotMatch",
"type": "n8n-nodes-base.switch",
"typeVersion": 3,
"position": [1320, 720],
"alwaysOutputData": false
},
{
"parameters": {
"rules": {
"values": [
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "17eb6574-9578-4915-8365-772e08d2f06b",
"leftValue": "={{ $json.test }}",
"rightValue": "/^value$/g",
"operator": {
"type": "string",
"operation": "regex"
}
}
],
"combinator": "and"
}
}
]
},
"options": {
"fallbackOutput": "extra"
}
},
"id": "07776b86-1d7c-4435-b7d8-da73a01830cf",
"name": "Match",
"type": "n8n-nodes-base.switch",
"typeVersion": 3,
"position": [1320, 340],
"alwaysOutputData": false
},
{
"parameters": {
"rules": {
"values": [
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "17eb6574-9578-4915-8365-772e08d2f06b",
"leftValue": "={{ $json.test }}",
"rightValue": "^value$",
"operator": {
"type": "string",
"operation": "regex"
}
}
],
"combinator": "and"
}
}
]
},
"options": {
"fallbackOutput": "extra"
}
},
"id": "9fb71a7e-23aa-44f6-ae75-cfc4dc045b81",
"name": "Match1",
"type": "n8n-nodes-base.switch",
"typeVersion": 3,
"position": [1320, 500],
"alwaysOutputData": false
},
{
"parameters": {
"rules": {
"values": [
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "17eb6574-9578-4915-8365-772e08d2f06b",
"leftValue": "={{ $json.test }}",
"rightValue": "^value$",
"operator": {
"type": "string",
"operation": "notRegex"
}
}
],
"combinator": "and"
}
}
]
},
"options": {
"fallbackOutput": "extra"
}
},
"id": "555125fe-6509-4b68-8e3d-bf643f9b4d09",
"name": "NotMatch1",
"type": "n8n-nodes-base.switch",
"typeVersion": 3,
"position": [1320, 880],
"alwaysOutputData": false
},
{
"parameters": {},
"id": "a8d5d282-cff3-4bbf-8293-67b1bbb08e2f",
"name": "Output1",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1640, 480]
},
{
"parameters": {},
"id": "3b7cf77e-f435-4863-a63d-db716cd27528",
"name": "Fallback1",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1680, 740]
}
],
"pinData": {
"Output": [
{
"json": {
"test": "value"
}
}
],
"Fallback": [
{
"json": {
"test": "value"
}
}
],
"Output1": [
{
"json": {
"test": "value"
}
}
],
"Fallback1": [
{
"json": {
"test": "value"
}
}
]
},
"connections": {
"When clicking Execute workflow": {
"main": [
[
{
"node": "Edit Fields",
"type": "main",
"index": 0
}
]
]
},
"Edit Fields": {
"main": [
[
{
"node": "Match",
"type": "main",
"index": 0
},
{
"node": "NotMatch",
"type": "main",
"index": 0
},
{
"node": "Match1",
"type": "main",
"index": 0
},
{
"node": "NotMatch1",
"type": "main",
"index": 0
}
]
]
},
"NotMatch": {
"main": [
[],
[
{
"node": "Fallback1",
"type": "main",
"index": 0
}
]
]
},
"Match": {
"main": [
[
{
"node": "Output",
"type": "main",
"index": 0
}
]
]
},
"NotMatch1": {
"main": [
[],
[
{
"node": "Fallback",
"type": "main",
"index": 0
}
]
]
},
"Match1": {
"main": [
[
{
"node": "Output1",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {
"executionOrder": "v1"
},
"versionId": "1fdad78e-d569-48c8-bbb9-640e8889b8e3",
"meta": {
"templateCredsSetupCompleted": true,
"instanceId": "8c8c5237b8e37b006a7adce87f4369350c58e41f3ca9de16196d3197f69eabcd"
},
"id": "EbLiIKvBYzJvLtX3",
"tags": []
}
@@ -0,0 +1,241 @@
{
"name": "My workflow 64",
"nodes": [
{
"parameters": {},
"id": "2c6504d1-9412-4da5-bd51-e5f9d6a84721",
"name": "When clicking \"Execute Workflow\"",
"type": "n8n-nodes-base.manualTrigger",
"typeVersion": 1,
"position": [-560, 620]
},
{
"parameters": {
"data": [
{
"output": "third",
"text": "third output text"
},
{
"output": "fourth",
"text": "fourth output text"
},
{
"output": "first",
"text": "first output text"
},
{
"output": "second",
"text": "second output text"
}
]
},
"id": "73d838de-89f2-476e-9dc8-a4dc59e4bdfb",
"name": "Code",
"type": "n8n-nodes-testing.testData",
"typeVersion": 1,
"position": [-340, 620]
},
{
"parameters": {},
"id": "d19a786e-e9fc-4480-af8a-c1abc9d9ef9a",
"name": "No Operation, do nothing",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [200, 460]
},
{
"parameters": {},
"id": "82d5a7b9-6a29-4df8-823a-bd926f2000a9",
"name": "No Operation, do nothing1",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [200, 620]
},
{
"parameters": {},
"id": "40276b8e-eaad-49bd-9271-cd82c6688f24",
"name": "No Operation, do nothing2",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [200, 780]
},
{
"parameters": {
"rules": {
"values": [
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"leftValue": "={{ $json.output }}",
"rightValue": "first",
"operator": {
"type": "string",
"operation": "equals"
}
}
],
"combinator": "and"
},
"renameOutput": true,
"outputKey": "First Output"
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "199d4f8c-1c92-48cd-99ad-e1da186ed54f",
"leftValue": "={{ $json.output }}",
"rightValue": "second",
"operator": {
"type": "string",
"operation": "equals",
"name": "filter.operator.equals"
}
}
],
"combinator": "and"
},
"renameOutput": true,
"outputKey": "Second Output"
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "e894662a-7496-4df4-a084-7200c3192485",
"leftValue": "={{ $json.output }}",
"rightValue": "third",
"operator": {
"type": "string",
"operation": "equals",
"name": "filter.operator.equals"
}
}
],
"combinator": "and"
},
"renameOutput": true,
"outputKey": "Third Output"
}
]
},
"options": {
"fallbackOutput": 2
}
},
"id": "0c34bae5-89c8-4adb-bb38-092d5a0e349e",
"name": "Switch1",
"type": "n8n-nodes-base.switch",
"typeVersion": 3,
"position": [-120, 620]
}
],
"pinData": {
"No Operation, do nothing": [
{
"json": {
"output": "first",
"text": "first output text"
}
}
],
"No Operation, do nothing1": [
{
"json": {
"output": "second",
"text": "second output text"
}
}
],
"No Operation, do nothing2": [
{
"json": {
"output": "third",
"text": "third output text"
}
},
{
"json": {
"output": "fourth",
"text": "fourth output text"
}
}
]
},
"connections": {
"When clicking \"Execute Workflow\"": {
"main": [
[
{
"node": "Code",
"type": "main",
"index": 0
}
]
]
},
"Code": {
"main": [
[
{
"node": "Switch1",
"type": "main",
"index": 0
}
]
]
},
"Switch1": {
"main": [
[
{
"node": "No Operation, do nothing",
"type": "main",
"index": 0
}
],
[
{
"node": "No Operation, do nothing1",
"type": "main",
"index": 0
}
],
[
{
"node": "No Operation, do nothing2",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {
"executionOrder": "v1"
},
"versionId": "c9c4d7fd-b704-4664-8fde-d1c2414e68f0",
"id": "1vDZkJN9SpYXu0Ic",
"meta": {
"instanceId": "b888bd11cd1ddbb95450babf3e199556799d999b896f650de768b8370ee50363"
},
"tags": []
}