# Switch (Route)

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

Source: https://docs.sommatic.ai/zh/nodes/flow.switch/

- 标识: `flow.switch`
- 类别: 流程控制
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

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

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

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

**适用场景：**
- 按状态路由订单（例如 'pending' -> 端口 A，'shipped' -> 端口 B）。
- 按优先级对支持工单分类。
- 在 webhook 中处理不同的事件类型。

## 配置

- `cases` (array<object>, 必填): 定义条件及其对应的输出端口。
- `first_match` (boolean, 可选): 启用后，只激活第一个匹配的端口；禁用时，激活所有匹配的端口（多播）。 默认值: `true`.

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

## 输出端口

- `default` (默认): 没有任何 case 匹配时激活。
- `error`: 发生求值错误时激活。

## 输入契约

- `payload` (object, 必填)

## 输出契约

- `payload` (object, 可选)

## 在表达式中

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

- `$("Switch (Route)").item.json.payload` (object) **worker 不返回：读取结果为 undefined.**
- `$("Switch (Route)").item.json.order_id` (string) = `"ord_125"` (编辑器不提示)
- `$("Switch (Route)").item.json.amount` (number) = `40` (编辑器不提示)
- `$("Switch (Route)").item.json.status` (string) = `"active"` (编辑器不提示)


## 工作原理

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

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`。

## 在工作流中

### 节点

```json
{
  "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
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "order_id": "ord_123",
    "amount": 1250,
    "status": "active"
  },
  "port": "high_value",
  "meta": {
    "matched": [
      "high_value"
    ]
  }
}
```

## 输出端口 (代码中的行为)

### `default`

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

```json
{
  "order_id": "ord_125",
  "amount": 40,
  "status": "active"
}
```

### `error`

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

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

## 代码中的行为

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

## 错误

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

## 说明与限制

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


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "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
    }
  }
}
```

### config_schema

```json
{
  "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

```json
{
  "type": "object",
  "description": "The JSON payload to be evaluated against the switch cases.",
  "properties": {
    "payload": {
      "type": "object"
    }
  },
  "required": [
    "payload"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The original payload is passed through to the matched output port(s).",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "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."
  }
]
```
