n8n 中文文档

选择您的节点构建方式

n8n 有两种节点构建样式:声明式和编程式。请使用声明式样式构建节点,这是新节点的默认样式。

声明式样式:

  • 使用基于 JSON 的语法,编写起来更简单,引入错误的风险也更低。
  • 更具前瞻性。
  • 支持与 REST API 集成。
  • 不需要 execute() 方法,因此要编写和维护的代码更少。

如果不确定节点需要哪种样式,请从声明式样式开始。n8n-node 工具可为您搭建声明式节点的脚手架,构建声明式样式节点则通过一个完整示例介绍整个过程。

何时需要编程式样式

编程式样式更为冗长,并且会将节点行为放入需要您维护的代码中,因此应将其视为例外。以下类型的节点需要使用编程式样式:

  • 触发器节点。
  • 不基于 REST 的节点。这包括需要调用 GraphQL API 的节点,以及使用外部依赖项的节点。
  • 需要执行 routing 无法处理的数据转换的节点。声明式样式可以使用 routing.request.preSend 修改请求,并使用 routing.output.postReceive 修改 API 响应。如果节点需要独立于单次 API 调用来处理传入的数据项,请使用编程式样式。
  • 需要基于功能的版本控制,并使用 this.isNodeFeatureEnabled() 在代码中分支行为的节点。声明式节点仍可使用轻量版本控制,也可以在 displayOptions 中通过 @feature 读取功能标志。有关版本控制类型的更多信息,请参阅节点版本控制。

如果您的节点不在此列表中,请使用声明式样式构建。

提示

触发器节点必须使用编程式样式

声明式样式不支持触发器节点。所有触发器节点都必须使用编程式样式构建,即使同一服务的操作节点使用声明式样式也是如此。

你可以在同一个节点包中混用两种样式。例如,提交验证的包可以同时包含同一服务的声明式操作节点和编程式触发器节点。

数据处理差异

声明式风格和编程式风格之间的主要区别在于它们如何处理传入数据和构建 API 请求。编程风格需要 execute() 方法,该方法读取传入的数据和参数,然后构建请求。声明式样式使用 operations 对象中的 routing 键来处理此问题。有关节点参数和 execute() 方法的更多信息,请参阅 节点基础文件。

语法差异

要了解声明式和编程式样式之间的区别,请比较下面的两个代码片段。此示例创建了 SendGrid 集成的简化版本,称为"FriendGrid"。以下代码片段并不完整:它们强调了节点构建样式的差异。

FriendGrid 调用 REST API,并且不会转换输入,因此声明式样式是正确选择。声明式样式的代码如下:

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

// 创建 FriendGrid 类
export class FriendGrid implements INodeType {
  description: INodeTypeDescription = {
    displayName: 'FriendGrid',
    name: 'friendGrid',
    . . .
    // 设置基本请求配置
    requestDefaults: {
      baseURL: 'https://api.sendgrid.com/v3/marketing'
    },
    properties: [
      {
        displayName: 'Resource',
        . . .
      },
      {
        displayName: 'Operation',
        name: 'operation',
        type: 'options',
        displayOptions: {
          show: {
            resource: [
              'contact',
            ],
          },
        },
        options: [
          {
            name: 'Create',
            value: 'create',
            description: 'Create a contact',
            // 添加 routing 对象
            routing: {
              request: {
                method: 'POST',
                url: '=/contacts',
                send: {
                  type: 'body',
                  properties: {
                    email: '={{$parameter["email"]}}'
                  }
                }
              },
              // 处理创建联系人的响应
              output: {
                postReceive: [
                  {
                    type: 'set',
                    properties: {
                      value: '={{ { "success": $response } }}'
                    }
                  }
                ]
              }
            }
          },
        ],
        default: 'create',
        description: 'The operation to perform.',
      },
      {
        displayName: 'Email',
        . . .
      },
      {
        displayName: 'Additional Fields',
        // 设置可选字段
      },
    ],
  }
  // 不需要 execute 方法
}

同一节点使用编程式样式时,需要用 execute() 方法读取参数并手动构建请求:

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

// 创建 FriendGrid 类
export class FriendGrid implements INodeType {
  description: INodeTypeDescription = {
    displayName: 'FriendGrid',
    name: 'friendGrid',
    . . .
    properties: [
      {
        displayName: 'Resource',
        . . .
      },
      {
        displayName: 'Operation',
        name: 'operation',
        type: 'options',
        displayOptions: {
          show: {
              resource: [
              'contact',
              ],
          },
        },
        options: [
          {
            name: 'Create',
            value: 'create',
            description: 'Create a contact',
          },
        ],
        default: 'create',
        description: 'The operation to perform.',
      },
      {
        displayName: 'Email',
        name: 'email',
        . . .
      },
      {
        displayName: 'Additional Fields',
        // 设置可选字段
      },
    ],
};

  async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
    let responseData;
    const resource = this.getNodeParameter('resource', 0) as string;
    const operation = this.getNodeParameter('operation', 0) as string;
    //获取用户为此节点提供的凭据
    const credentials = await this.getCredentials('friendGridApi') as IDataObject;

    if (resource === 'contact') {
      if (operation === 'create') {
      // 获取电子邮件输入
      const email = this.getNodeParameter('email', 0) as string;
      // 获取附加字段输入
      const additionalFields = this.getNodeParameter('additionalFields', 0) as IDataObject;
      const data: IDataObject = {
          email,
      };

      Object.assign(data, additionalFields);

      // 按照 https://sendgrid.com/docs/api-reference/ 中定义的方式发出 HTTP 请求
      const options: IRequestOptions = {
        headers: {
            'Accept': 'application/json',
            'Authorization': `Bearer ${credentials.apiKey}`,
        },
        method: 'PUT',
        body: {
            contacts: [
            data,
            ],
        },
        url: `https://api.sendgrid.com/v3/marketing/contacts`,
        json: true,
      };
      responseData = await this.helpers.httpRequest(options);
      }
    }
    // 将数据映射到 n8n 数据
    return [this.helpers.returnJsonArray(responseData)];
  }
}

相关资源

不想自己部署和维护 n8n?n8ncn 托管 n8n 云服务:开通账号即可使用,不用买服务器;也可以在 n8ncn 工作流库 找现成的中文工作流。