构建编程式节点
本教程逐步介绍如何构建编程式节点。开始前,请确认这正是所需的开发方式,更多信息请参阅选择节点开发方式。
前提条件
开发机器需要安装以下工具:
- Git
- Node.js 和 npm,Node 最低版本为 18.17.0。在 Linux、Mac 和 WSL 中,可按照 nvm 安装说明,使用 nvm(Node Version Manager)安装两者。Windows 用户请参阅微软的 Windows 上安装 NodeJS指南。
译注:此共用片段仍列 Node 18.17.0,而同一版本“设置开发环境”页面要求最低 Node 22.22.0。此处保留两处原文并提示差异,不据此推断所用 n8n 或开发工具版本的实际兼容范围。
还需要了解:
- JavaScript/TypeScript
- REST API
- Git
- n8n 中的表达式1
构建节点
本节将克隆 n8n 节点入门仓库,构建集成 SendGrid 的节点,实现 SendGrid 的一项功能:创建联系人。
已有节点
n8n 已内置 SendGrid 节点。为避免冲突,本教程的版本将使用不同名称。
第一步:设置项目
n8n 提供节点开发入门仓库,确保包含所需的全部依赖,并提供 linter。
克隆仓库并进入目录:
- 根据模板仓库生成新仓库。
- 克隆新仓库:
shell git clone https://github.com/<your-organization>/<your-repo-name>.git n8n-nodes-friendgrid cd n8n-nodes-friendgrid
入门项目包含示例节点和凭据,请删除以下目录和文件:
nodes/Examplenodes/GithubIssuescredentials/GithubIssuesApi.credentials.tscredentials/GithubIssuesOAuth2Api.credentials.ts
然后创建以下目录和文件:
nodes/FriendGrid
nodes/FriendGrid/FriendGrid.node.json
nodes/FriendGrid/FriendGrid.node.ts
credentials/FriendGridApi.credentials.ts
这些是所有节点必需的关键文件。必需文件和推荐组织方式的更多说明,请参阅节点文件结构。
现在安装项目依赖:
npm i
第二步:添加图标
将 SendGrid SVG 标志另存为 friendGrid.svg,放入 nodes/FriendGrid/。
n8n 建议使用 SVG 作为节点图标,也可使用 PNG。如果使用 PNG,分辨率应为 60×60 像素。节点图标的宽高比应为正方形或接近正方形。
不要直接引用 Font Awesome
如果希望在节点中使用 Font Awesome 图标,请下载图片并嵌入。不要设置 defaults.color:它仅用于为 Font Awesome 图标着色,n8n 3.0 会将其移除。
第三步:在基础文件中定义节点
每个节点都必须有基础文件,参数详情请参阅节点基础文件。
此示例使用 FriendGrid.node.ts 文件。为简化教程,节点全部功能都放在这一个文件中。构建更复杂的节点时,应考虑按模块拆分功能。更多信息请参阅节点文件结构。
第 3.1 步:导入
先添加导入语句:
import type {
IDataObject,
IExecuteFunctions,
IHttpRequestOptions,
INodeExecutionData,
INodeType,
INodeTypeDescription,
} from 'n8n-workflow';
import { NodeConnectionTypes } from 'n8n-workflow';
第 3.2 步:创建主类
节点必须导出一个实现 INodeType 的类。类的 description 配置对象必须包含 properties 数组。
类名与文件名
请确保类名与文件名匹配。例如,类名为 FriendGrid 时,文件名必须为 FriendGrid.node.ts。
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:
displayName: 'FriendGrid',
name: 'friendGrid',
icon: 'file:friendGrid.svg',
group: ['transform'],
version: 1,
description: 'Consume SendGrid API',
defaults: {
name: 'FriendGrid',
},
inputs: [NodeConnectionTypes.Main],
outputs: [NodeConnectionTypes.Main],
usableAsTool: true,
credentials: [
{
name: 'friendGridApi',
required: true,
},
],
n8n 使用 description 中的部分属性在编 辑器界面渲染节点,包括 displayName、icon 和 description。
第 3.4 步:添加资源
资源对象定义节点使用的 API 资源。本教程的节点访问 SendGrid 的 /v3/marketing/contacts 端点,因此需为此端点定义资源。将资源对象添加到 properties 数组:
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Contact',
value: 'contact',
},
],
default: 'contact',
noDataExpression: true,
required: true,
description: 'Create a new contact',
},
type 控制 n8n 为资源显示哪种界面元素,并指定用户应输入的数据类型。options 会添加一个供用户单选的下拉菜单。更多信息请参阅节点界面元素。