# Encoders

> Base64 与 URL 查询字符串。

Source: https://docs.sommatic.ai/zh/expressions/reference/encoders/

每个示例都在已部署的表达式引擎上、基于页面末尾的[示例上下文](#example-context)运行过。

## `$base64Encode`

函数 · `string` · 来源: `Link Loom SDK · utilities.encoder.base64.encode`

```javascript
$base64Encode(value)
```

使用 URL 安全的 Base64 字母表（以 `-` 和 `_` 代替 `+` 和 `/`）对 `value` 编码，且不带 `=` 填充。字符串按 UTF-8 编码；其他值先序列化为 JSON。空值（`''`、`null`、`undefined`、`0`、`false`）返回空字符串。

### 参数

- `value` (string | object, 必填): 要编码的文本或值。

### 返回

`string`: 不带填充的 URL 安全 Base64 文本。

### 示例

```javascript
{{ $base64Encode('Sommatic') }}
```

结果 (string):

```json
"U29tbWF0aWM"
```

```javascript
{{ $base64Encode({ order: $json.body.order_id }) }}
```

结果 (string):

```json
"eyJvcmRlciI6Im9yZF8xMDQyIn0"
```

```javascript
{{ $base64Encode('') }}
```

结果 (string):

```json
""
```

### 说明

- 部分服务要求带填充的标准 Base64（例如 `Basic` 授权头）。请转换结果：`{{ (function(){ var b = $base64Encode(text).replace(/-/g, '+').replace(/_/g, '/'); return b + '==='.slice((b.length + 3) % 4); })() }}`，或为节点绑定凭据，而不必自行构造请求头。

在 JSONata 中: `$$base64Encode(body.order_id)`

## `$base64Decode`

函数 · `string` · 来源: `Link Loom SDK · utilities.encoder.base64.decode`

```javascript
$base64Decode(text)
```

解码标准或 URL 安全的 Base64（带或不带填充），并以 UTF-8 文本返回结果。它从不报错：字母表以外的字符会被跳过。要从编码的 JSON 还原对象，请用 `JSON.parse` 解析该文本。

### 参数

- `text` (string, 必填): Base64 文本。

### 返回

`string`: 解码后的文本；值为空时返回空字符串。

### 示例

```javascript
{{ $base64Decode('U29tbWF0aWM') }}
```

结果 (string):

```json
"Sommatic"
```

还原为对象。

```javascript
{{ JSON.parse($base64Decode('eyJvcmRlciI6Im9yZF8xMDQyIn0')) }}
```

结果 (object):

```json
{
  "order": "ord_1042"
}
```

### 说明

- 二进制内容（PDF、图片）经文本转换后会损坏：请在代码节点中解码，或交给处理该文件的节点完成。

在 JSONata 中: `$$base64Decode(body.state)`

## `$toQueryString`

函数 · `string` · 来源: `Link Loom SDK · utilities.encoder.object.toQueryString`

```javascript
$toQueryString(object)
```

由对象构建查询字符串，对键和值进行百分号编码。嵌套对象和列表使用方括号（`filter[status]`、`ids[0]`），同样经过编码。结果以 `?` 开头，可直接追加到 URL 后；非对象参数返回空字符串。

### 参数

- `object` (object, 必填): 参数，每个键对应一个参数。

### 返回

`string`: `?key=value&…`；参数不是对象时为 `''`。

### 示例

```javascript
https://api.example.com/orders{{ $toQueryString({ status: 'open', page: 2 }) }}
```

结果 (string):

```json
"https://api.example.com/orders?status=open&page=2"
```

```javascript
{{ $toQueryString({ q: $json.body.customer.name, filter: { segment: 'gold' } }) }}
```

结果 (string):

```json
"?q=Ana%20P%C3%A9rez&filter%5Bsegment%5D=gold"
```

```javascript
{{ $toQueryString({ ids: ['A-100', 'C-300'] }) }}
```

结果 (string):

```json
"?ids%5B0%5D=A-100&ids%5B1%5D=C-300"
```

false、0 和空字符串会以 null 发送。

```javascript
{{ $toQueryString({ active: false, retries: 0 }) }}
```

结果 (string):

```json
"?active=null&retries=null"
```

### 说明

- `false`、`0` 和 `''` 会变成文本 `null`。请以字符串形式传入（`'false'`、`'0'`），或自行编写这部分 URL。

在 JSONata 中: `$$toQueryString({ "status": "open" })`

## 示例上下文

示例基于以下数据运行：当前节点的输入（`$json`）、已运行的节点（`$(…)`）、本次运行的 ID 以及当前节点。时钟固定为 `2026-11-26T14:30:00.000Z`，服务器时区为 UTC，因此各页面中 `$now` 与 `$today` 的值都相同。

```json
{
  "$json": {
    "body": {
      "order_id": "ord_1042",
      "email": "ana.perez@example.com",
      "customer": {
        "name": "Ana Pérez",
        "segment": "gold"
      },
      "priority": "",
      "items": [
        {
          "sku": "A-100",
          "qty": 2,
          "price": 10.5
        },
        {
          "sku": "B-200",
          "qty": 0,
          "price": 4
        },
        {
          "sku": "C-300",
          "qty": 1,
          "price": 25
        }
      ],
      "tags": [
        "new",
        "web",
        "new"
      ],
      "created_at": "2026-11-25T09:15:00Z"
    },
    "headers": {
      "content-type": "application/json"
    },
    "query": {},
    "method": "POST"
  },
  "nodes": {
    "Webhook Receiver": "= $json",
    "Normalize input": {
      "correlation_id": "c-7f3a",
      "channel": "web"
    },
    "Classify": {
      "label": "billing",
      "confidence": 0.92
    }
  },
  "run": {
    "$flow_instance_result_id": "fir-xxxx",
    "$flow_instance_id": "fi-xxxx",
    "$flow_definition_id": "fd-xxxx",
    "$flow_version_id": "fv-xxxx",
    "$flow_slug": "order-intake"
  },
  "node": {
    "node_id": "node-notify",
    "label": "Notify customer"
  }
}
```

串联工作流的示例基于第二个上下文运行：一个由 `workflow.chain` 启动的工作流，其 `workflow.trigger` 节点的标签为 `Chain Entry Point`。

```json
{
  "$json": {
    "order_id": "ord_1042",
    "customer_email": "ana.perez@example.com",
    "amount": 46,
    "chain_context": {
      "caller_flow_definition_id": "fd-caller-xxxx",
      "caller_flow_instance_id": "fi-caller-xxxx",
      "caller_flow_slug": "order-intake",
      "caller_node_id": "node-chain-billing",
      "correlation_id": "chain-7Hq2Lw9sKd3pXa1mZr4t",
      "root_flow_instance_result_id": "fir-root-xxxx"
    }
  },
  "run": {
    "$flow_instance_result_id": "fir-hop-xxxx",
    "$flow_instance_id": "fi-hop-xxxx",
    "$flow_definition_id": "fd-billing-xxxx",
    "$flow_version_id": "fv-billing-xxxx",
    "$flow_slug": "billing-review",
    "$input": {
      "data": {
        "order_id": "ord_1042",
        "customer_email": "ana.perez@example.com",
        "amount": 46
      },
      "chain_context": {
        "caller_flow_definition_id": "fd-caller-xxxx",
        "caller_flow_instance_id": "fi-caller-xxxx",
        "caller_flow_slug": "order-intake",
        "caller_node_id": "node-chain-billing",
        "correlation_id": "chain-7Hq2Lw9sKd3pXa1mZr4t",
        "root_flow_instance_result_id": "fir-root-xxxx"
      }
    }
  },
  "node": {
    "node_id": "node-create-task",
    "label": "Create review task"
  }
}
```

示例运行所基于的编排器提交 31e874b.
