本页内容
Sommatic 文档
打开控制台

Switch (Route)

根据匹配条件,将执行流路由到多个端口之一。

以 Markdown 查看
在以下应用中打开
流程控制 可用 flow.switch 版本 1.0.0 执行方式: sync

按顺序评估路由用例,将原样的 payload 从第一个匹配用例指定的端口输出,否则走 default。

该算子的作用类似 switch-case 或 if-else-if 链。它按顺序评估已定义的“cases”列表,第一个表达式为真的 case 会触发其对应的输出端口。若没有任何 case 匹配,执行将路由到“default”端口。

行为:

  • 顺序评估: 按定义顺序检查各个 case。
  • 首个匹配: 默认在第一个为真的条件后停止。
  • 默认路径: 所有条件都不满足时,激活“default”端口。

适用场景:

  • 按状态路由订单(例如 'pending' -> 端口 A,'shipped' -> 端口 B)。
  • 按优先级对支持工单分类。
  • 在 webhook 中处理不同的事件类型。

工作原理

  1. 解析配置:每个用例 expr 中的 {{ }} 由 Expression Engine 求值。
  2. 若 cases 不是数组,payload 走 default。
  3. 跳过 port 为空或解析后 expr 为假值(false、0、""、undefined)的用例。
  4. 布尔型 expr 直接使用;其他值作为 JSONata 针对 payload 求值(amount > 1000)。
  5. 收集每个为真用例的端口;first_match 为 true(默认)时在第一个匹配处停止。
  6. 将 payload 从第一个匹配端口输出,并在 meta.matched 中列出所有匹配;若无匹配则走 default。

在工作流中

节点在工作流文件(draft_nodes[])中的写法,以及一次成功运行的 envelope。

{
  "node_id": "node-route-order",
  "label": "Route order",
  "operator_slug": "flow.switch",
  "operator_version": "1.0.0",
  "config": {
    "cases": [
      {
        "expr": "{{ $json.amount > 1000 }}",
        "port": "high_value"
      },
      {
        "expr": "status = \"on_hold\"",
        "port": "on_hold"
      }
    ],
    "first_match": true
  }
}

配置

cases array<object> 必填

定义条件及其对应的输出端口。

first_match boolean 可选

启用后,只激活第一个匹配的端口;禁用时,激活所有匹配的端口(多播)。

默认值: true

配置中会显示通用执行设置,但该节点目前不执行重试(retryOnFail、maxTries)。所有节点均未实现 continueOnFail。

代码中的行为

除 schema 描述之外,实现代码对这些键的实际处理。

cases
每个用例为 { expr, port }。用例端口是自定义名称(^[a-z0-9_-]+$),必须与某条连线的 from.port 一致;匹配的端口若没有连线,分支即结束。定义中的示例 $json.amount > 1000(不带 {{ }})永远不会匹配,因为 JSONata 中没有绑定 $json:请写 amount > 1000 或 {{ $json.amount > 1000 }}。
first_match
为 false 时会评估所有用例并列在 meta.matched 中,但只有第一个匹配端口会触发:不支持多路输出。

输出端口

default 默认

没有用例匹配,或 cases 不是数组。用例匹配时,同样的 payload 会从该用例指定的端口输出。

数据
{
  "order_id": "ord_125",
  "amount": 40,
  "status": "active"
}
error

某个用例无法作为 JSONata 编译或求值。

数据
{
  "ok": false,
  "errors": [
    "Switch evaluation error: <JSONata message>"
  ],
  "port": "error"
}

在表达式中

后续节点可通过 $("Switch (Route)").item.json.<路径> 读取此节点输出中的内容(请把 Switch (Route) 换成你的节点标签)。Editor 标记工作流编辑器在 Previous Nodes 中提示的路径(输出契约);Worker 标记 worker 实际通过 default 返回的路径,依据“端口”一节所示的输出。

表达式EditorWorker
$("Switch (Route)").item.json.payloadobjectworker 不返回:读取结果为 undefined —
$("Switch (Route)").item.json.order_idstring编辑器不提示= "ord_125"—
$("Switch (Route)").item.json.amountnumber编辑器不提示= 40—
$("Switch (Route)").item.json.statusstring编辑器不提示= "active"—

— Editor: 编辑器会提示它,但 worker 并不返回:读取结果为 undefined。

— Worker: worker 会返回它,但编辑器不会提示:请手动输入。对象内部的键可能取决于你的数据或配置(例如每个标签一个键)。

错误

消息 端口 原因与处理
Switch evaluation error: <JSONata message> error 某个用例的 expr 不是有效 JSONata。first_match 为 true 时,匹配之后的用例不会再求值。
Switch evaluation error: path.charAt is not a function error 某个用例的 {{ }} 返回了非零数字、对象或数组。请返回布尔值。

输入契约

payload object 必填

输出契约

payload object 可选

契约(JSON Schema)

与编排器声明完全一致的定义。All 是完整的 *.definition.js;可与上方各节对照,找出文档与 schema 之间的差异。发布前可用它校验节点。

{
  "slug": "flow.switch",
  "name": "Switch (Route)",
  "category": "flow",
  "version": "1.0.0",
  "description": "Routes the execution flow to one of multiple ports based on a matching condition.\n\n  This operator functions similarly to a switch-case or if-else-if ladder. It evaluates a list of defined 'cases' in order. The first case whose expression evaluates to true triggers its corresponding output port. If no cases match, execution is routed to the 'default' port.\n\n  **Behavior:**\n  - **Sequential Evaluation:** Cases are checked in the order defined.\n  - **First Match:** By default, stops after the first true condition.\n  - **Default Path:** If no conditions are met, the 'default' port is activated.\n\n  **Use Cases:**\n  - Routing orders based on status (e.g., 'pending' -> Port A, 'shipped' -> Port B).\n  - Categorizing support tickets by priority.\n  - Handling different event types in a webhook.",
  "capabilities": [
    "branching",
    "logic",
    "jsonata",
    "router"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "cases"
    ],
    "properties": {
      "cases": {
        "type": "array",
        "title": "Routing Cases",
        "description": "Define the conditions and their corresponding output ports.",
        "items": {
          "type": "object",
          "properties": {
            "expr": {
              "type": "string",
              "title": "Condition Expression",
              "format": "expression",
              "description": "Expression that must evaluate to true. Use the Expression Editor for JavaScript with full variable access, or enter raw JSONata without {{ }} (see jsonata.org). Example: $json.amount > 1000"
            },
            "port": {
              "type": "string",
              "title": "Output Port Name",
              "description": "The name of the port to signal if this case matches (e.g., \"high_value\").",
              "pattern": "^[a-z0-9_-]+$"
            }
          },
          "required": [
            "expr",
            "port"
          ]
        }
      },
      "first_match": {
        "type": "boolean",
        "title": "Stop on First Match",
        "default": true,
        "description": "If enabled, only the first matching port is activated. If disabled, all matching ports are activated (multicast)."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "description": "The JSON payload to be evaluated against the switch cases.",
    "properties": {
      "payload": {
        "type": "object"
      }
    },
    "required": [
      "payload"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The original payload is passed through to the matched output port(s).",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "default",
      "label": "Default",
      "is_default": true,
      "description": "Activated when no cases match."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Activated if an evaluation error occurs."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "logic",
    "router",
    "multi-path",
    "conditional"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}

执行

执行方式
sync
有状态
否
重试(retryOnFail)
否
能力
branchinglogicjsonatarouter
标签
logicroutermulti-pathconditional

说明与限制

  • from.port 为 * 的连线无论触发哪个端口都会收到 payload。
  • meta 只记录在运行步骤中:下游节点收到的 payload 是 data,无法通过 $json 或 $("Node") 读取 meta。
  • 当返回的信封没有 data(或 data 为假值)时,引擎会把整个信封作为节点输出:经 error 端口时,下一个节点收到的 payload 是 { ok: false, errors: [...], port: "error" }。

已对照编排器代码核实 · 31e874b · 2026-11-26

安装智能体工具

为你的编程智能体接入 Sommatic AI 官方文档:技能包、文档 MCP 服务器与 Markdown 页面,无需再抓取网页。

安装 Sommatic AI CLI,并为检测到的智能体配置合适的插件。

npx @sommatic/cli agent setup
智能体如何读取本文档