GraphQL
这是什么 / 何时用
Graphql 服务允许开发者使用标准 GraphQL query(只读查询)与 mutation(数据变更)语句访问平台数据面资源(如 Account、Users、Teams、TablesDB/Databases、Storage、Functions 等),其底层权限校验、行级安全(RLS)与配额限流体系同 REST 接口完全一致。
在前端聚合页面或复杂 BFF(Backend For Frontend)场景中(如演示项目 enterprise-ai-hub-210 同时需要读取当前登录账号信息、所属团队列表以及工单表 customer_tickets 的摘要数据),使用 GraphQL 可在一次 HTTP 请求中按需裁剪返回字段并组合多个查询,减少多轮往返开销与冗余字段传输。
前置
- 客户端初始化与认证:
- Server SDK(Node.js / Java / Python / Go):通过
setEndpoint('https://appbuild-sit.oceanbase.com/v1')、setProject('enterprise-ai-hub-210')、setKey('<APPBASE_API_KEY>') 初始化;API Key 需具备所查询/变更底层资源对应的 scope(如 users.read、tables.read、rows.write 等)。 - Client / Web SDK:通过
setEndpoint、setProject 初始化并完成用户登录(Session 或 JWT),查询范围严格受当前用户 Session 与表/行级权限(Permissions)约束。 - Console SDK:支持管理面 Session 或短期 JWT。
使用骨架
- **初始化客户端与
Graphql 服务**:构造 Client 并实例化 new Graphql(client)。 - **执行只读查询(
graphql.query)**:传入包含 query(GraphQL 查询字符串)及可选 variables(参数化变量对象)、operationName 的 JSON 载荷,从返回对象的 data 字段读取按需投影的结果。 - **执行数据变更(
graphql.mutation)**:传入 mutation 变更语句与 variables(如创建行、更新偏好设置、创建团队等),确保所有动态用户输入均通过 $variable 变量绑定传入,切勿直接拼接 GraphQL 字符串。 - **校验业务级
errors 数组**:GraphQL 规范下,即使部分或全部字段解析失败,HTTP 状态码通常仍为 200;调用方必须在拿到响应后优先检查 response.errors 是否非空。
关键参数与返回
方法与请求载荷
| SDK 方法(Node / Web / Java / Python) | Go 方法 | REST 端点 | 请求参数(query 载荷对象) | 说明 |
|---|
query({ query }) | Query(query) | POST /v1/graphql | { query: string, variables?: object, operationName?: string } | 执行 GraphQL 只读查询或变更请求。 |
mutation({ query }) | Mutation(query) | POST /v1/graphql/mutation | { query: string, variables?: object, operationName?: string } | 专用于执行 GraphQL mutation 变更操作的语义化入口。 |
请求体字段明细
| 字段 | 类型 | 必填 | 约束 / 默认值 | 说明 |
|---|
query | string | 是 | 非空 GraphQL 文档串 | 标准 GraphQL query 或 mutation 语句,支持片段(Fragment)与变量声明。 |
variables | object | 否 | 默认 {} | 变量键值映射表,对应 GraphQL 语句中声明的 $varName 参数。 |
operationName | string | 否 | 字符串 | 当 query 文档内包含多个命名操作时,指定本次执行的操作名。 |
返回结构(GraphQL 标准响应包络)
| 字段 | 类型 | 说明 |
|---|
data | object \ | null | 按查询 Selection Set 投影返回的业务数据对象;若顶层执行失败则为 null。 |
errors | object[](可选) | 执行或语法校验错误列表。每项含 message(错误描述)、locations([{ line, column }])、path(出错字段路径)及可选 extensions。 |
错误与边界
- **HTTP 200 与 GraphQL
errors[] 的双层错误处理**: - 网络中断、网关不可达、项目不存在(
404)或请求频率超限(429)会抛出 AgentbaseException(或返回非 2xx HTTP 状态码)。 - GraphQL 语法错误、字段名不存在、目标资源無权限或单字段 resolver 报错时,HTTP 状态码仍为 **
200 OK**,错误信息写入响应 JSON 的 errors 数组。业务代码**必须同时捕获 AgentbaseException 并检查 result.errors**。
- 统一限流配额:GraphQL 接口与 REST 接口共享项目限流体系(默认单端点限流 60 次/分钟),触发限流时返回
429 rate_limit_exceeded 及 Retry-After 响应头。 - 查询深度与复杂度限制:为防止嵌套循环查询耗尽内存,服务端限制单次 GraphQL 查询的最大嵌套深度与节点复杂度;批量拉取大表行数据时仍建议配合
queries 游标分页(limit + cursorAfter)。 - 严禁字符串拼接注入:动态查询条件必须写入
variables 字典并通过 GraphQL 变量(如 mutation($name: String!))引用,防止 GraphQL 结构注入。
SDK 类别差异
| SDK 类别 | 支持范围 | 鉴权方式 | 典型场景 |
|---|
| Server SDK(Node.js / Java / Python / Go) | query、mutation 全量 | 项目 API Key(按实际访问资源校验 scope) | 后端 BFF 聚合查询、跨模块批量数据组装 |
| Client / Web SDK(Web) | query、mutation 全量 | 用户 Session / JWT(受 RLS 行级权限约束) | 前端单页应用一次请求拉取用户信息与业务列表 |
| Console SDK(Node.js / Java / Python / Go) | query、mutation 全量 | 管理面 Session / 短期 JWT | 管理后台自定义聚合查询 |
各语言调用示例
客户端与服务端均可用;Web 页签走用户 Session,受数据面权限约束。
- Node.js(Server)
- Web(用户 Session)
- Java
- Python
- Go
- REST(curl)
import { Client, Graphql, AgentbaseException } from 'agentbase-node-sdk';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT ?? 'https://appbuild-sit.oceanbase.com/v1')
.setProject(process.env.APPBASE_PROJECT_ID ?? 'enterprise-ai-hub-210')
.setKey(process.env.APPBASE_API_KEY!);
const graphql = new Graphql(client);
try {
// 1. 执行只读查询(带参数化 variables)
const queryRes: any = await graphql.query({
query: {
query: `query GetLocaleAndDatabases {
localeGet { countryCode country currency }
tablesDBList { total databases { _id name } }
}`,
variables: {},
},
});
if (queryRes.errors?.length) {
console.error('GraphQL 业务错误:', queryRes.errors);
} else {
console.log('查询结果:', queryRes.data);
}
// 2. 执行变更(mutation)
const mutationRes: any = await graphql.mutation({
query: {
query: `mutation CreateSupportTeam($teamId: String!, $name: String!) {
teamsCreate(teamId: $teamId, name: $name) { _id name total }
}`,
variables: {
teamId: 'team_tier2_support',
name: '二线技术支持专家组',
},
},
});
if (mutationRes.errors?.length) {
console.error('GraphQL 变更错误:', mutationRes.errors);
}
} catch (err) {
if (err instanceof AgentbaseException) {
console.error(`HTTP 异常 [${err.code} ${err.type}]: ${err.message}`);
}
throw err;
}
import { Client, Graphql } from 'agentbase-web-sdk'; // 前提:用户已在浏览器完成登录
const client = new Client()
.setEndpoint('https://appbuild-sit.oceanbase.com/v1')
.setProject('enterprise-ai-hub-210');
const graphql = new Graphql(client);
const result = await graphql.query({
query: {
query: 'query { accountGet { _id name email status } localeGet { country currency } }',
},
});
if (result.errors) {
console.error('GraphQL errors:', result.errors);
} else {
console.log('Account & Locale:', result.data);
}
import io.agentbase.Client;
import io.agentbase.services.Graphql;
import io.agentbase.exceptions.AppBaseException;
import java.util.Map;
Client client = new Client()
.setEndpoint("https://appbuild-sit.oceanbase.com/v1")
.setProject("enterprise-ai-hub-210")
.setKey(System.getenv("APPBASE_API_KEY"));
Graphql graphql = new Graphql(client);
try {
Object result = graphql.query(Map.of(
"query", "query { localeGet { countryCode country currency } }"
));
Object mutationResult = graphql.mutation(Map.of(
"query", "mutation CreateTeam($teamId: String!, $name: String!) { teamsCreate(teamId: $teamId, name: $name) { _id name } }",
"variables", Map.of("teamId", "team_tier2_support", "name", "二线技术支持专家组")
));
System.out.println(result);
System.out.println(mutationResult);
} catch (AppBaseException e) {
System.err.println("HTTP " + e.getCode() + " type=" + e.getType() + ": " + e.getMessage());
}
import os
from agentbase.client import Client
from agentbase.services.graphql import Graphql
from agentbase.exception import AgentbaseException
client = (
Client()
.set_endpoint(os.environ.get('APPBASE_ENDPOINT', 'https://appbuild-sit.oceanbase.com/v1'))
.set_project(os.environ.get('APPBASE_PROJECT_ID', 'enterprise-ai-hub-210'))
.set_key(os.environ['APPBASE_API_KEY'])
)
graphql = Graphql(client)
try:
result = graphql.query(query={
'query': 'query { localeGet { countryCode country currency } }'
})
if isinstance(result, dict) and result.get('errors'):
print('GraphQL errors:', result['errors'])
graphql.mutation(query={
'query': 'mutation CreateTeam($teamId: String!, $name: String!) { teamsCreate(teamId: $teamId, name: $name) { _id name } }',
'variables': {'teamId': 'team_tier2_support', 'name': '二线技术支持专家组'},
})
except AgentbaseException as exc:
print(f"GraphQL HTTP error {exc.code} ({exc.type}): {exc.message}")
package main
import (
"fmt"
"os"
"agentbase-go-sdk/agentbase"
)
func main() {
cl := agentbase.NewClient(
agentbase.WithEndpoint("https://appbuild-sit.oceanbase.com/v1"),
agentbase.WithProject("enterprise-ai-hub-210"),
agentbase.WithKey(os.Getenv("APPBASE_API_KEY")),
)
graphql := agentbase.NewGraphql(cl)
result, err := graphql.Query(map[string]interface{}{
"query": "query { localeGet { countryCode country currency } }",
})
fmt.Println(result, err)
_, _ = graphql.Mutation(map[string]interface{}{
"query": "mutation CreateTeam($teamId: String!, $name: String!) { teamsCreate(teamId: $teamId, name: $name) { _id name } }",
"variables": map[string]interface{}{"teamId": "team_tier2_support", "name": "二线技术支持专家组"},
})
}
# 1. 执行只读查询(POST /v1/graphql)
curl -sS -X POST "$APPBASE_ENDPOINT/graphql" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{
"query": "query { localeGet { countryCode country currency } }",
"variables": {}
}'
# 2. 执行数据变更(POST /v1/graphql/mutation)
curl -sS -X POST "$APPBASE_ENDPOINT/graphql/mutation" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{
"query": "mutation CreateTeam($teamId: String!, $name: String!) { teamsCreate(teamId: $teamId, name: $name) { _id name } }",
"variables": {
"teamId": "team_tier2_support",
"name": "二线技术支持专家组"
}
}'
示例指引
事实源
skills/ob-agentbase/references/server-sdks/nodejs.md(模块表)apis/zh-CN/misc/graphql.md(REST 端点与 GraphQL 协议说明)- appbase
release-2.10.2 / v2.10.0(0a5d23f9349028496286572fd43117aa6f8fce0a) - agentbase-sdks v2.10.0 specs(
packages/sdks/server-nodejs/src/services/graphql.ts 方法面)