# GraphQL Client

> 执行 GraphQL 查询或变更（Mutation）。

Source: https://docs.sommatic.ai/zh/nodes/io.graphql/

- 标识: `io.graphql`
- 类别: 输入与输出
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

执行 GraphQL 查询或变更（Mutation）。

## 配置

- `connection_id` (string, 必填): GraphQL 端点的凭据。接受 `api-key`、`basic-auth` 或 `oauth2`（bearer token）类型的凭据。
- `query` (string, 必填): GraphQL 查询/变更
- `variables` (object, 可选)

## 输出端口

- `out` (默认): GraphQL 数据响应
- `error`: GraphQL 错误或网络错误

## 输入契约

- `connection_id` (string, 必填)
- `query` (string, 必填)
- `variables` (object, 可选)

## 输出契约

- `data` (object, 可选): GraphQL 数据
- `errors` (array, 可选): GraphQL 错误

## 在表达式中

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

- `$("GraphQL Client").item.json.data` (object) = `{…}`: GraphQL 数据
- `$("GraphQL Client").item.json.errors` (array): GraphQL 错误 **worker 不返回：读取结果为 undefined.**
- `$("GraphQL Client").item.json.data.order` (object) = `{…}` (编辑器不提示)


## 工作原理

以 HTTP POST 向凭据中的端点发送一次 GraphQL 查询或变更，返回 `data`，或通过 error 端口返回 GraphQL `errors`。

1. 解析配置。`connection_id`、`query` 和 `variables` 缺失时回退到输入 payload 中的同名键；`connection_id` 和 `query` 为必填。
2. 解析凭据。端点为 `config.url`（或 `config.endpoint`）；附加请求头取自 `config.headers`。
3. 根据密钥添加认证，按顺序首个匹配生效：`token` → `Authorization: Bearer`，`apiKey` → 请求头 `config.headerName`（默认 `x-api-key`），`username` + `password` → `Authorization: Basic`。
4. 以 JSON 格式 POST `{ query, variables }`。
5. 若响应中 `errors` 数组非空，则从 `error` 输出 `{ errors }`；否则从 `out` 返回 `{ data }`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-fetch-order",
  "label": "Fetch order",
  "operator_slug": "io.graphql",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "query": "query Order($id: ID!) { order(id: $id) { id status } }",
    "variables": {
      "id": "{{ $json.order_id }}"
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "data": {
      "order": {
        "id": "ord_123",
        "status": "PAID"
      }
    }
  },
  "port": "out"
}
```

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

### `out`

服务器返回 2xx 且无 GraphQL 错误。`data` 为 GraphQL 响应中的 `data` 字段。

```json
{
  "data": {
    "order": {
      "id": "ord_123",
      "status": "PAID"
    }
  }
}
```

### `error`

响应包含 GraphQL `errors`（数据为 `{ errors }`），或请求失败（数据为 `{ error, response }`，其中 `response` 为非 2xx 响应的正文）。

```json
{
  "errors": [
    {
      "message": "Cannot query field \"stat\" on type \"Order\".",
      "locations": [
        {
          "line": 1,
          "column": 32
        }
      ]
    }
  ]
}
```

## 代码中的行为

- `connection_id`: 接受密钥为对象（含 `token`、`apiKey` 或 `username` + `password`）的 `basic-auth`、`oauth2` 和 `object` 凭据。以纯字符串保存的 `api-key` 凭据不会添加任何请求头。以 `http` 开头的值会直接用作端点 URL，不带认证。
- `variables`: 按原样发送；其中的表达式会先被解析。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `connection_id is required` | `error` | 未选择凭据。请选择一个 GraphQL 凭据。 |
| `query is required` | `error` | 配置和输入 payload 中的查询均为空。 |
| `Request failed with status code <status>` | `error` | 服务器返回非 2xx 状态，`response` 中包含其正文。请检查端点和认证。 |
| `Failed to resolve connection <connection_id>: <detail>` | `error` | 凭据不存在或此工作流无权使用。 |

## 说明与限制

- 同时包含 `data` 和 `errors` 的响应（部分成功）会进入 `error`，部分 `data` 将被丢弃。
- 请求不设超时，也不会重试。


## 契约（JSON Schema）

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

```json
{
  "slug": "io.graphql",
  "name": "GraphQL Client",
  "category": "io",
  "version": "1.0.0",
  "description": "Execute GraphQL Query or Mutation.",
  "capabilities": [
    "graphql",
    "api",
    "http"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "GraphQL Credential",
        "description": "Credential for the GraphQL endpoint. Accepts credentials of type `api-key`, `basic-auth`, or `oauth2` (bearer token).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "api-key",
            "basic-auth",
            "oauth2"
          ],
          "types": [
            "graphql",
            "http"
          ]
        }
      },
      "query": {
        "type": "string",
        "description": "GraphQL Query/Mutation"
      },
      "variables": {
        "type": "object"
      }
    },
    "required": [
      "connection_id",
      "query"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "query": {
        "type": "string"
      },
      "variables": {
        "type": "object"
      }
    },
    "required": [
      "connection_id",
      "query"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "data": {
        "type": "object",
        "description": "GraphQL Data"
      },
      "errors": {
        "type": "array",
        "description": "GraphQL Errors"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Data",
      "description": "GraphQL data response",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Errors",
      "description": "GraphQL errors or network error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io"
  ],
  "tags": [
    "graphql",
    "api"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "GraphQL Credential",
      "description": "Credential for the GraphQL endpoint. Accepts credentials of type `api-key`, `basic-auth`, or `oauth2` (bearer token).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "api-key",
          "basic-auth",
          "oauth2"
        ],
        "types": [
          "graphql",
          "http"
        ]
      }
    },
    "query": {
      "type": "string",
      "description": "GraphQL Query/Mutation"
    },
    "variables": {
      "type": "object"
    }
  },
  "required": [
    "connection_id",
    "query"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "query": {
      "type": "string"
    },
    "variables": {
      "type": "object"
    }
  },
  "required": [
    "connection_id",
    "query"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "description": "GraphQL Data"
    },
    "errors": {
      "type": "array",
      "description": "GraphQL Errors"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Data",
    "description": "GraphQL data response",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Errors",
    "description": "GraphQL errors or network error",
    "is_default": false,
    "supports_condition": false
  }
]
```
