跳至内容

构建一个编程风格的节点#

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

先决条件#

您需要在开发机器上安装以下内容:

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

你需要了解以下内容:

  • JavaScript/TypeScript
  • REST API接口
  • git
  • Expressions 在 n8n 中

构建你的节点#

在本节中,您将克隆n8n的节点入门仓库,并构建一个集成SendGrid的节点。您将创建一个实现SendGrid一项功能的节点:添加联系人。

现有节点

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

步骤1:设置项目#

n8n提供了一个用于节点开发的基础代码库。使用该基础库可确保您拥有所有必要的依赖项。它还提供了代码检查工具。

克隆仓库并进入目录:

  1. Generate a new repository 从模板仓库生成一个新仓库。
  2. 克隆您的新仓库:
    1
    2
    git clone https://github.com//.git n8n-nodes-friendgrid
    cd n8n-nodes-friendgrid
    

入门包包含示例节点和凭证。请删除以下目录和文件:

  • 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标志从这里保存为friendGrid.svgnodes/FriendGrid/目录下。

n8n推荐使用SVG格式作为节点图标,但您也可以使用PNG。如果选择PNG格式,图标分辨率应为60x60像素。节点图标的长宽比应保持正方形或接近正方形。

不要引用Font Awesome

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

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

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

在本示例中,文件名为FriendGrid.node.ts。为保持教程简洁,我们将把所有节点功能集中在这个文件中。当构建更复杂的节点时,建议将功能拆分为多个模块。更多信息请参阅Node file structure

步骤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:创建主类#

节点必须导出一个实现INodeType接口的对象。该接口必须包含一个description接口,而该接口又包含properties数组。

类名和文件名

确保类名与文件名匹配。例如,给定一个类 FriendGrid,文件名必须是 FriendGrid.node.ts

 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: 添加节点详情#

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

 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使用description中设置的部分属性在编辑器界面渲染节点。这些属性包括displayNameicondescription

步骤 3.4: 添加资源#

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

 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',
},

type 控制n8n为资源显示的UI元素类型,并告知n8n预期从用户处获取的数据类型。options会导致n8n添加一个下拉菜单,允许用户选择其中一个选项。更多信息请参阅Node UI elements

步骤 3.5: 添加操作#

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

将以下内容添加到properties数组中,位于resource对象之后:

 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在用户界面中将它们显示在附加字段下。

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

 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请求,并使节点真正执行某些操作了。

execute方法在节点每次运行时都会执行。在此方法中,您可以访问输入项以及用户在界面中设置的参数,包括凭据信息。

将以下内容添加到FriendGrid.node.ts中的execute方法里:

 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;
	...
}

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

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

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

步骤5:设置认证#

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

将以下内容添加到 FriendGridApi.credentials.ts

 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',
		},
	};
}

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

步骤6:添加节点元数据#

关于您节点的元数据信息存放在节点根目录下的JSON文件中。n8n将此称为codex文件。在本示例中,该文件是FriendGrid.node.json

将以下代码添加到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": ""
			}
		]
	}
}

有关这些参数的更多信息,请参阅节点代码文件

步骤7: 更新npm包详情#

您的npm包详细信息位于项目根目录下的package.json文件中。必须包含带有凭证和基础节点文件链接的n8n对象。请更新此文件以包含以下信息:

 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
	}
}

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

测试你的节点#

你可以在本地n8n实例中运行节点来测试正在构建的节点。

  1. 使用npm安装n8n:
    1
    npm install n8n -g
    
  2. 当您准备好测试节点时,请先在本地发布:
    1
    2
    3
    # 在您的节点目录中
    npm run build
    npm link
    
  3. 将节点安装到您的本地n8n实例中:

    1
    2
    3
    # 在n8n安装目录的nodes文件夹中
    # node-package-name是package.json中的名称
    npm link <node-package-name>
    

    检查您的目录

    请确保在您的n8n安装目录下的nodes文件夹中运行npm link <node-name>命令。路径可能是:

    • ~/.n8n/custom/
    • ~/.n8n/<your-custom-name>: 如果你的n8n安装使用了N8N_CUSTOM_EXTENSIONS设置了不同的名称。
  4. 启动n8n:

    1
    n8n start
    

  5. 在浏览器中打开n8n。在节点面板中搜索时,您应该能看到您的节点。

    节点名称

    请确保使用节点名称而非包名称进行搜索。例如,如果您的npm包名为n8n-nodes-weather-nodes,而该包包含名为rainsunsnow的节点,您应该搜索rain,而不是weather-nodes

故障排除#

  • 本地安装的~/.n8n目录中没有custom子目录。

你需要手动创建custom目录并运行npm init

1
2
3
4
# 在~/.n8n目录下运行
mkdir custom 
cd custom 
npm init

下一步#

优云智算