跳至内容

构建声明式风格节点#

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

先决条件#

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

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

你需要了解以下内容:

  • JavaScript/TypeScript
  • REST API接口
  • git

构建你的节点#

在本节中,您将克隆n8n的节点入门代码库,并构建一个集成NASA API的节点。您将创建一个使用NASA两项服务的节点:APOD(每日天文图片)和火星探测器照片。为了保持代码示例简洁,该节点不会实现火星探测器照片端点的所有可用选项。

现有节点

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

步骤1:设置项目#

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

克隆仓库并进入目录:

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

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

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

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

nodes/NasaPics
nodes/NasaPics/NasaPics.node.json
nodes/NasaPics/NasaPics.node.ts
credentials/NasaPicsApi.credentials.ts

以下是任何节点所需的关键文件。有关必需文件和推荐组织结构的更多信息,请参阅节点文件结构

现在安装项目依赖项:

1
npm i

步骤2:添加图标#

将NASA的SVG标志从这里保存为nasapics.svgnodes/NasaPics/目录下。

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

不要引用Font Awesome

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

步骤3:创建节点#

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

在本示例中,文件是NasaPics.node.ts。为了使本教程简洁,您将把所有节点功能都放在这个文件中。当构建更复杂的节点时,应考虑将功能拆分到不同模块中。更多信息请参阅Node file structure

步骤3.1:导入#

首先添加导入语句:

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

步骤3.2:创建主类#

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

类名和文件名

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

1
2
3
4
5
6
7
8
export class NasaPics implements INodeType {
	description: INodeTypeDescription = {
		// Basic node details will go here
		properties: [
		// Resources and operations will go here
		]
	};
}

步骤 3.3: 添加节点详情#

所有节点都需要一些基本参数,例如它们的显示名称、图标以及使用该节点发起请求的基本信息。将以下内容添加到description中:

 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
displayName: 'NASA Pics',
name: 'NasaPics',
icon: 'file:nasapics.svg',
group: ['transform'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Get data from NASAs API',
defaults: {
	name: 'NASA Pics',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
	{
		name: 'NasaPicsApi',
		required: true,
	},
],
requestDefaults: {
	baseURL: 'https://api.nasa.gov',
	headers: {
		Accept: 'application/json',
		'Content-Type': 'application/json',
	},
},

n8n使用description中设置的部分属性在编辑器界面渲染节点。这些属性包括displayNameicondescriptionsubtitle

步骤 3.4: 添加资源#

资源对象定义了节点所使用的API资源。在本教程中,您将创建一个节点来访问NASA的两个API端点:planetary/apodmars-photos。这意味着您需要在NasaPics.node.ts中定义两个资源选项。使用资源对象更新properties数组:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
properties: [
	{
		displayName: 'Resource',
		name: 'resource',
		type: 'options',
		noDataExpression: true,
		options: [
			{
				name: 'Astronomy Picture of the Day',
				value: 'astronomyPictureOfTheDay',
			},
			{
				name: 'Mars Rover Photos',
				value: 'marsRoverPhotos',
			},
		],
		default: 'astronomyPictureOfTheDay',
	},
	// Operations will go here

]

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

步骤 3.5: 添加操作#

operations对象定义了资源上可用的操作。

在声明式节点中,operations对象包含routing(位于options数组内)。这用于设置API调用的详细信息。

将以下内容添加到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
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
{
	displayName: 'Operation',
	name: 'operation',
	type: 'options',
	noDataExpression: true,
	displayOptions: {
		show: {
			resource: [
				'astronomyPictureOfTheDay',
			],
		},
	},
	options: [
		{
			name: 'Get',
			value: 'get',
			action: 'Get the APOD',
			description: 'Get the Astronomy Picture of the day',
			routing: {
				request: {
					method: 'GET',
					url: '/planetary/apod',
				},
			},
		},
	],
	default: 'get',
},
{
	displayName: 'Operation',
	name: 'operation',
	type: 'options',
	noDataExpression: true,
	displayOptions: {
		show: {
			resource: [
				'marsRoverPhotos',
			],
		},
	},
	options: [
		{
			name: 'Get',
			value: 'get',
			action: 'Get Mars Rover photos',
			description: 'Get photos from the Mars Rover',
			routing: {
				request: {
					method: 'GET',
				},
			},
		},
	],
	default: 'get',
},
{
	displayName: 'Rover name',
	description: 'Choose which Mars Rover to get a photo from',
	required: true,
	name: 'roverName',
	type: 'options',
	options: [
		{name: 'Curiosity', value: 'curiosity'},
		{name: 'Opportunity', value: 'opportunity'},
		{name: 'Perseverance', value: 'perseverance'},
		{name: 'Spirit', value: 'spirit'},
	],
	routing: {
		request: {
			url: '=/mars-photos/api/v1/rovers/{{$value}}/photos',
		},
	},
	default: 'curiosity',
	displayOptions: {
		show: {
			resource: [
				'marsRoverPhotos',
			],
		},
	},
},
{
	displayName: 'Date',
	description: 'Earth date',
	required: true,
	name: 'marsRoverDate',
	type: 'dateTime',
	default:'',
	displayOptions: {
		show: {
			resource: [
				'marsRoverPhotos',
			],
		},
	},
	routing: {
		request: {
			// You've already set up the URL. qs appends the value of the field as a query string
			qs: {
				earth_date: '={{ new Date($value).toISOString().substr(0,10) }}',
			},
		},
	},
},
// Optional/additional fields will go here

这段代码创建了两个操作:一个用于获取今天的APOD(每日天文图片)图像,另一个用于发送获取火星探测器照片的请求。名为roverName的对象要求用户选择他们想要获取哪个探测器的照片。火星探测器操作中的routing对象引用此参数来构建API调用的URL。

步骤 3.6: 可选字段#

大多数API,包括本示例中使用的NASA API,都提供可选字段用于优化查询。

为了避免让用户感到不知所措,n8n在用户界面中将它们显示在附加字段下。

在本教程中,您需要添加一个额外字段,允许用户选择日期与APOD端点配合使用。将以下内容添加到属性数组中:

 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
{
	displayName: 'Additional Fields',
	name: 'additionalFields',
	type: 'collection',
	default: {},
	placeholder: 'Add Field',
	displayOptions: {
		show: {
			resource: [
				'astronomyPictureOfTheDay',
			],
			operation: [
				'get',
			],
		},
	},
	options: [
		{
			displayName: 'Date',
			name: 'apodDate',
			type: 'dateTime',
			default: '',
			routing: {
				request: {
					// You've already set up the URL. qs appends the value of the field as a query string
					qs: {
						date: '={{ new Date($value).toISOString().substr(0,10) }}',
					},
				},
			},
		},
	],									
}

步骤4:设置认证#

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

将以下内容添加到 nasaPicsApi.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
import {
	IAuthenticateGeneric,
	ICredentialType,
	INodeProperties,
} from 'n8n-workflow';

export class NasaPicsApi implements ICredentialType {
	name = 'NasaPicsApi';
	displayName = 'NASA Pics API';
	// Uses the link to this tutorial as an example
	// Replace with your own docs links when building your own nodes
	documentationUrl = 'https://docs.n8n.io/integrations/creating-nodes/build/declarative-style-node/';
	properties: INodeProperties[] = [
		{
			displayName: 'API Key',
			name: 'apiKey',
			type: 'string',
			default: '',
		},
	];
	authenticate = {
		type: 'generic',
		properties: {
			qs: {
				'api_key': '={{$credentials.apiKey}}'
			}
		},
	} as IAuthenticateGeneric;
}

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

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

关于您节点的元数据信息存放在节点根目录下的JSON文件中。n8n将此称为codex文件。在本示例中,该文件是NasaPics.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.NasaPics",
	"nodeVersion": "1.0",
	"codexVersion": "1.0",
	"categories": [
		"Miscellaneous"
	],
	"resources": {
		"credentialDocumentation": [
			{
				"url": ""
			}
		],
		"primaryDocumentation": [
			{
				"url": ""
			}
		]
	}
}

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

步骤6:更新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-nasapics",
	"version": "0.1.0",
	"description": "n8n node to call NASA's APOD and Mars Rover Photo services.",
	"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/NasaPicsApi.credentials.js"
		],
		"nodes": [
			"dist/nodes/NasaPics/NasaPics.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

下一步#

优云智算