属性验证

了解不同类型的属性验证

Activepieces 使用 Zod 进行 Piece 属性的运行时验证。Zod 提供了强大的模式验证系统,有助于确保你的 Piece 接收有效的输入。

要在你的 Piece 中使用 Zod 验证,首先导入验证助手和 Zod:

请确保 `minimumSupportedRelease` 至少设置为 `0.36.1`,验证才能正常工作。
import { createAction, Property } from '@activepieces/pieces-framework';
import { propsValidation } from '@activepieces/pieces-common';
import { z } from 'zod';

export const getIcecreamFlavor = createAction({
  name: 'get_icecream_flavor', // 动作的唯一名称。
  displayName: '获取冰淇淋口味',
  description: '根据用户偏好获取随机冰淇淋口味。',
  props: {
    sweetnessLevel: Property.Number({
      displayName: '甜度等级',
      required: true,
      description: '指定甜度等级(0 到 10)。',
    }),
    includeToppings: Property.Checkbox({
      displayName: '包含配料',
      required: false,
      description: '口味是否应包含配料?',
      defaultValue: true,
    }),
    numberOfFlavors: Property.Number({
      displayName: '口味数量',
      required: true,
      description: '你想获取多少种口味?(1-5)',
      defaultValue: 1,
    }),
  },
  async run({ propsValue }) {
    // 使用 Zod 验证输入属性
    await propsValidation.validateZod(propsValue, {
      sweetnessLevel: z.number().min(0).max(10, '甜度等级必须在 0 到 10 之间。'),
      numberOfFlavors: z.number().min(1).max(5, '你可以获取 1 到 5 种口味。'),
    });

    // 动作逻辑
    const sweetnessLevel = propsValue.sweetnessLevel;
    const includeToppings = propsValue.includeToppings ?? true; // 默认为 true
    const numberOfFlavors = propsValue.numberOfFlavors;

    // 模拟获取随机冰淇淋口味
    const allFlavors = [
      '香草',
      '巧克力',
      '草莓',
      '薄荷',
      '曲奇面团',
      '开心果',
      '芒果',
      '咖啡',
      '咸焦糖',
      '黑莓',
    ];
    const selectedFlavors = allFlavors.slice(0, numberOfFlavors);

    return {
      message: `以下是你的 ${numberOfFlavors} 种口味:${selectedFlavors.join(', ')}`,
      sweetnessLevel: sweetnessLevel,
      includeToppings: includeToppings,
    };
  },
});