Skip to content

构建程序化风格的节点

本教程将指导您构建一个程序化风格的节点。开始之前,请确保这是您需要的节点样式。有关更多信息,请参阅选择您的节点构建方法

先决条件

您需要在开发机器上安装以下软件:

  • git
  • Node.js 和 npm。最低版本 Node 18.17.0。您可以在此处找到有关如何在 Linux、Mac 和 WSL 上使用 nvm(Node 版本管理器)安装两者的说明。对于 Windows 用户,请参阅 Microsoft 的“在 Windows 上安装 NodeJS”指南。

您需要了解以下内容:

  • JavaScript/TypeScript
  • REST API
  • git
  • n8n 中的表达式

构建你的节点

在本节中,您将克隆 n8n 的节点启动器存储库,并构建一个集成SendGrid 的节点。您将创建一个实现 SendGrid 一项功能的节点:创建联系人。

现有节点

n8n 内置了 SendGrid 节点。为了避免与现有节点冲突,您需要为您的版本指定一个不同的名称。

步骤 1:设置项目

n8n 提供了一个用于 Node 开发的入门仓库。使用该入门仓库可以确保您拥有所有必要的依赖项。它还提供了一个 Linter 工具。

克隆存储库并导航到目录:

  1. 从模板存储库生成一个新的存储库
  2. 克隆您的新存储库:

启动器包含示例节点和凭证。删除以下目录和文件:

  • nodes/ExampleNode
  • nodes/HTTPBin
  • credentials/ExampleCredentials.credentials.ts
  • credentials/HttpBinApi.credentials.ts

现在创建以下目录和文件:

nodes/FriendGrid
nodes/FriendGrid/FriendGrid.node.json
nodes/FriendGrid/FriendGrid.node.ts
credentials/FriendGridApi.credentials.ts

这些是任何节点所需的关键文件。有关所需文件和建议组织方式的更多信息,请参阅节点文件结构

现在安装项目依赖项:

1
npm i

第 2 步:添加图标

这里将 SendGrid SVG 徽标保存为。

n8n 建议使用 SVG 作为节点图标,但您也可以使用 PNG。如果使用 PNG,图标分辨率应为 60x60px。节点图标的长宽比应为正方形或近似正方形。

不要引用 Font Awesome

如果您想在节点中使用 Font Awesome 图标,请下载并嵌入该图像。

步骤 3:在基础文件中定义节点

每个节点都必须有一个基础文件。有关基础文件参数的详细信息,请参阅节点基础文件

在此示例中,文件为。为了简化本教程,您将把所有节点功能放在一个文件中。构建更复杂的节点时,应考虑将功能拆分为模块。有关更多信息,请参阅Node 文件结构

步骤 3.1:导入

首先添加导入语句:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import {
	IExecuteFunctions,
} from 'n8n-core';

import {
	IDataObject,
	INodeExecutionData,
	INodeType,
	INodeTypeDescription,
} from 'n8n-workflow';

import {
	OptionsWithUri,
} from 'request';

步骤 3.2:创建主类

该节点必须导出一个实现 的接口。该接口必须包含一个接口,该接口又包含数组。

类名和文件名

确保类名和文件名匹配。例如,给定一个类,文件名必须是。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
export class FriendGrid implements INodeType {
	description: INodeTypeDescription = {
		// Basic node details will go here
		properties: [
			// Resources and operations will go here
		],
	};
	// The execute method will go here
	async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
	}
}

步骤 3.3:添加节点详细信息

所有编程节点都需要一些基本参数,例如其显示名称和图标。将以下内容添加到:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
displayName: 'FriendGrid',
name: 'friendGrid',
icon: 'file:friendGrid.svg',
group: ['transform'],
version: 1,
description: 'Consume SendGrid API',
defaults: {
	name: 'FriendGrid',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
	{
		name: 'friendGridApi',
		required: true,
	},
],

n8n 使用 中设置的一些属性在编辑器 UI 中渲染节点。这些属性包括、和。

步骤 3.4:添加资源

资源对象定义节点使用的 API 资源。在本教程中,您将创建一个节点来访问 SendGrid 的 API 端点之一: 。这意味着您需要为此端点定义一个资源。使用资源对象更新数组:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
	displayName: 'Resource',
	name: 'resource',
	type: 'options',
	options: [
		{
			name: 'Contact',
			value: 'contact',
		},
	],
	default: 'contact',
	noDataExpression: true,
	required: true,
	description: 'Create a new contact',
},

控制 n8n 为资源显示哪个 UI 元素,并告知 n8n 期望从用户那里获得什么类型的数据。这将导致 n8n 添加一个下拉菜单,允许用户选择一个选项。有关更多信息,请参阅Node UI 元素

步骤 3.5:添加操作

操作对象定义了您可以对资源执行的操作。它通常与 REST API 动词(GET、POST 等)相关。在本教程中,有一个操作:创建联系人。它有一个必填字段,即用户创建的联系人的电子邮件地址。

在数组的对象之后添加以下内容:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
{
	displayName: 'Operation',
	name: 'operation',
	type: 'options',
	displayOptions: {
		show: {
			resource: [
				'contact',
			],
		},
	},
	options: [
		{
			name: 'Create',
			value: 'create',
			description: 'Create a contact',
			action: 'Create a contact',
		},
	],
	default: 'create',
	noDataExpression: true,
},
{
	displayName: 'Email',
	name: 'email',
	type: 'string',
	required: true,
	displayOptions: {
		show: {
			operation: [
				'create',
			],
			resource: [
				'contact',
			],
		},
	},
	default:'',
	placeholder: 'name@email.com',
	description:'Primary email for the contact',
},

步骤 3.6:添加可选字段

大多数 API(包括您在此示例中使用的 SendGrid API)都有可选字段,您可以使用它们来优化查询。

为了避免给用户带来过多的负担,n8n 将这些内容显示在 UI 中的“附加字段”下。

在本教程中,您将添加两个附加字段,以允许用户输入联系人的名字和姓氏。将以下内容添加到 properties 数组中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
{
	displayName: 'Additional Fields',
	name: 'additionalFields',
	type: 'collection',
	placeholder: 'Add Field',
	default: {},
	displayOptions: {
		show: {
			resource: [
				'contact',
			],
			operation: [
				'create',
			],
		},
	},
	options: [
		{
			displayName: 'First Name',
			name: 'firstName',
			type: 'string',
			default: '',
		},
		{
			displayName: 'Last Name',
			name: 'lastName',
			type: 'string',
			default: '',
		},
	],
},

步骤 4:添加执行方法

您已设置好节点 UI 和基本信息。现在是时候将节点 UI 映射到 API 请求,并让节点实际执行某些操作了。

该方法在节点每次运行时都会运行。在此方法中,您可以访问输入项以及用户在 UI 中设置的参数(包括凭据)。

在中添加以下方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Handle data coming from previous nodes
const items = this.getInputData();
let responseData;
const returnData = [];
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;

// For each item, make an API call to create a contact
for (let i = 0; i < items.length; i++) {
	if (resource === 'contact') {
		if (operation === 'create') {
			// Get email input
			const email = this.getNodeParameter('email', i) as string;
			// Get additional fields input
			const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
			const data: IDataObject = {
				email,
			};

			Object.assign(data, additionalFields);

			// Make HTTP request according to https://sendgrid.com/docs/api-reference/
			const options: OptionsWithUri = {
				headers: {
					'Accept': 'application/json',
				},
				method: 'PUT',
				body: {
					contacts: [
						data,
					],
				},
				uri: `https://api.sendgrid.com/v3/marketing/contacts`,
				json: true,
			};
			responseData = await this.helpers.requestWithAuthentication.call(this, 'friendGridApi', options);
			returnData.push(responseData);
		}
	}
}
// Map data to n8n data structure
return [this.helpers.returnJsonArray(returnData)];

请注意此代码的以下几行:

1
2
3
4
5
6
7
const items = this.getInputData();
... 
for (let i = 0; i < items.length; i++) {
	...
	const email = this.getNodeParameter('email', i) as string;
	...
}

用户可以通过两种方式提供数据:

  • 直接在节点字段中输入
  • 通过映射工作流中较早节点的数据

以及后续循环,使节点能够处理数据来自前一个节点的情况。这包括支持多个输入。这意味着,例如,如果前一个节点输出了五个人的联系信息,您的 FriendGrid 节点就可以创建五个联系人。

步骤 5:设置身份验证

SendGrid API 要求用户使用 API 密钥进行身份验证。

添加以下内容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import {
	IAuthenticateGeneric,
	ICredentialTestRequest,
	ICredentialType,
	INodeProperties,
} from 'n8n-workflow';

export class FriendGridApi implements ICredentialType {
	name = 'friendGridApi';
	displayName = 'FriendGrid API';
	properties: INodeProperties[] = [
		{
			displayName: 'API Key',
			name: 'apiKey',
			type: 'string',
			default: '',
		},
	];

	authenticate: IAuthenticateGeneric = {
		type: 'generic',
		properties: {
			headers: {
				Authorization: '=Bearer {{$credentials.apiKey}}',
			},
		},
	};

	test: ICredentialTestRequest = {
		request: {
			baseURL: 'https://api.sendgrid.com/v3',
			url: '/marketing/contacts',
		},
	};
}

有关凭证文件和选项的更多信息,请参阅凭证文件

步骤 6:添加节点元数据

节点的元数据存储在节点根目录下的 JSON 文件中。n8n 将其称为 codex 文件。在本例中,该文件为。

将以下代码添加到 JSON 文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
{
	"node": "n8n-nodes-base.FriendGrid",
	"nodeVersion": "1.0",
	"codexVersion": "1.0",
	"categories": [
		"Miscellaneous"
	],
	"resources": {
		"credentialDocumentation": [
			{
				"url": ""
			}
		],
		"primaryDocumentation": [
			{
				"url": ""
			}
		]
	}
}

有关这些参数的更多信息,请参阅Node codex 文件

步骤 7:更新 npm 包详细信息

您的 npm 软件包详细信息位于项目根目录下。务必包含指向凭据和基节点文件的链接对象。请更新此文件以包含以下信息:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
{
	// All node names must start with "n8n-nodes-"
	"name": "n8n-nodes-friendgrid",
	"version": "0.1.0",
	"description": "n8n node to create contacts in SendGrid",
	"keywords": [
		// This keyword is required for community nodes
		"n8n-community-node-package"
	],
	"license": "MIT",
	"homepage": "https://n8n.io",
	"author": {
		"name": "Test",
		"email": "test@example.com"
	},
	"repository": {
		"type": "git",
		// Change the git remote to your own repository
		// Add the new URL here
		"url": "git+<your-repo-url>"
	},
	"main": "index.js",
	"scripts": {
		// don't change
	},
	"files": [
		"dist"
	],
	// Link the credentials and node
	"n8n": {
		"n8nNodesApiVersion": 1,
		"credentials": [
			"dist/credentials/FriendGridApi.credentials.js"
		],
		"nodes": [
			"dist/nodes/FriendGrid/FriendGrid.node.js"
		]
	},
	"devDependencies": {
		// don't change
	},
	"peerDependencies": {
		// don't change
	}
}

您需要更新以包含您自己的信息,例如您的姓名和仓库 URL。有关 npm文件的更多信息,请参阅npm 的 package.json 文档

测试你的节点

您可以在构建节点时通过在本地 n8n 实例中运行它来测试它。

  1. 使用 npm 安装 n8n:
  2. 当您准备好测试节点时,请在本地发布它:
    • :如果您的 n8n 安装使用设置了不同的名称
  3. 启动 n8n:

    1
    n8n start
    
  4. 在浏览器中打开 n8n。在节点面板中搜索节点时,应该就能看到它们。

    节点名称

    确保使用节点名称(而不是包名称)进行搜索。例如,如果您的 npm 包名称是,并且该包包含名为、 、 的节点,则您应该搜索,而不是。

故障排除

  • 本地安装中没有目录。

您必须手动创建目录并运行

1
2
3
4
# In ~/.n8n directory run
mkdir custom 
cd custom 
npm init

后续步骤Next steps