Graffle 默认输出行为解析:开箱即用的类型安全 GraphQL 客户端数据返回

原创2026-10-09 18:23:322,305 阅读
文章标签:后端

Graffle 默认输出行为解析:开箱即用的类型安全 GraphQL 客户端数据返回

Graffle 是一个极简、可扩展、类型安全的 JavaScript GraphQL 客户端,其最引人注目的特点之一就是开箱即用的默认输出行为:无需任何配置,客户端即可把查询结果以"裸数据"(plain data)的形式直接返回给调用方。本文基于官方示例 output_default 与其配套的 示例文档,深入讲解 Graffle 默认输出的具体形态、背后的配置默认值、底层实现机制,以及如何通过 output 配置项切换到其他输出模式。

默认输出的核心示例:查询 pokemons

先看官方示例中最简单、最典型的一段代码。该示例位于 examples/20_output/output_default.ts(源码),对应的网页示例文档为 website/content/examples/20_output/default.md:

import { Graffle } from './graffle/_.js'

const pokemon = Graffle.create()

const pokemons = await pokemon.query.pokemons({ name: true })

console.log(pokemons)

执行这段查询后,控制台输出如下:

[
  { name: 'Pikachu' },
  { name: 'Charizard' },
  { name: 'Squirtle' },
  { name: 'Bulbasaur' },
  { name: 'Caterpie' },
  { name: 'Weedle' }
]

这里有三点值得注意:

  1. Graffle.create() 无参数调用:没有传入任何配置,意味着全程使用 Graffle 的默认配置;
  2. 查询语法:pokemon.query.pokemons({ name: true }) 是 Graffle 典型的 selection-set 风格调用——{ name: true } 表示只选择 name 字段,返回结果在类型层面被精确推导为 { name: string }[];
  3. 返回值形态:await 之后直接得到纯数据数组,而不是包裹着 data、errors 等字段的 GraphQL ExecutionResult 信封结构。

示例的运行环境说明

上述代码取自 Graffle 官方的示例目录(由脚本生成,见 scripts/generate-examples-derivatives/generate-docs.ts)。实际运行前,需要先执行 Graffle 的代码生成步骤,得到 ./graffle/_.js 与 ./graffle/modules/global.js 等生成模块。官方文档代码中有一段 Twoslash 专用注释也印证了这一点:

// Our website uses Vitepress+Twoslash. Twoslash does not discover the generated Graffle modules.
// Perhaps we can configure Twoslash to include them. Until we figure that out, we have to
// explicitly import them like this.
import './graffle/modules/global.js'

这段注释说明:在 Vitepress + Twoslash 的文档渲染环境中,Twoslash 无法自动发现生成后的 Graffle 模块,因此需要显式导入 ./graffle/modules/global.js 来注册全局类型。在实际业务项目中,如果你同样遇到 IDE 类型提示失效的问题,也可以采用同样的显式导入方式。

示例中对应的实际运行输出(由官方运行工具捕获)记录在 examples/outputs/20_output/output_default.output.txt:

---------------------------------------- SHOW ----------------------------------------
[
  { name: 'Pikachu' },
  { name: 'Charizard' },
  { name: 'Squirtle' },
  { name: 'Bulbasaur' },
  { name: 'Caterpie' },
  { name: 'Weedle' }
]

默认输出背后:output 配置项的默认值

"默认输出就是裸数据"并不是巧合,而是由 Graffle 输出配置(output)的一组规范化默认值决定的。该配置的完整定义位于 src/context/fragments/configuration/output/configuration.ts。

默认值一览

从源码中的 default_ 常量可以看到全部默认值:

const default_ = {
  defaults: {
    errorChannel: `throw`,   // 默认错误通道:抛出
  },
  envelope: {
    enabled: false,          // 默认不启用信封
    errors: {
      execution: true,
      other: false,
    },
  },
  errors: {
    execution: `default`,
    other: `default`,
  },
} satisfies Partial<Normalized>

对应地,配置项的类型定义(configuration.ts)如下:

配置路径 类型 默认值 含义
defaults.errorChannel 'throw' | 'return' 'throw' 默认错误通道,决定错误以抛出还是返回值形式出现
envelope boolean | object false 是否启用 ExecutionResult 信封包装
envelope.enabled boolean true(对象写法时) 信封开关
envelope.errors.execution boolean true 是否把执行错误放入信封的 errors 字段
envelope.errors.other boolean false 是否把其他错误(网络、扩展抛错等)放入信封
errors.execution 'throw' | 'return' | 'default' 'default' 执行错误通道,'default' 表示跟随 defaults.errorChannel
errors.other 'throw' | 'return' | 'default' 'default' 其他错误通道,同理

为什么默认得到"裸数据"

综合以上默认值,默认配置的净效果是:

  • envelope.enabled === false:响应不被包装成 { data, errors, ... } 信封,而是直接返回查询所选字段的纯数据;
  • defaults.errorChannel === 'throw':发生错误时默认抛出异常,而不是放进返回值。

因此,当查询成功时,await pokemon.query.pokemons({ name: true }) 直接得到 { name: string }[] 这样的类型安全裸数据;当查询失败时,错误被抛出,调用方通过 try/catch 捕获。这种"成功返回裸数据、失败抛异常"的组合,让 Graffle 的默认体验最接近普通异步函数调用的直觉。

从源码的 Normalized 类型(configuration.ts)还可以看到,运行时配置最终会被规范化成包含 defaults、envelope、errors 三个子对象的完整结构,示例中的 Graffle.create() 空参数调用即等于直接采用上述 default_ 默认值。

错误通道的解析规则:readErrorCategoryOutputChannel

默认配置中,errors.execution 与 errors.other 的值都是 'default'。源码为此提供了明确的解析函数 readErrorCategoryOutputChannel(configuration.ts):

export const readErrorCategoryOutputChannel = (
  output: Normalized,
  errorCategory: ErrorCategory,
): OutputChannel | false => {
  if (output.errors[errorCategory] === `default`) {
    return output.defaults.errorChannel
  }
  return output.errors[errorCategory]
}

该函数逻辑清晰:

  • 若某类错误的通道配置为 'default',则回退到 output.defaults.errorChannel(默认是 'throw');
  • 若显式配置为 'throw' 或 'return',则按显式值处理。

也就是说,你可以在 output.defaults.errorChannel 层面统一切换全局错误通道,也可以在 output.errors.execution / output.errors.other 层面按错误类别做精细化控制。默认情况下两类错误都走 'throw' 通道。

其他输出模式对比:Envelope 与 Standard GraphQL

理解了默认输出后,再来对比 Graffle 提供的其他输出模式会非常直观。官方在 website/content/examples/20_output/ 目录下按示例组织了一系列文档,分别对应不同配置。

信封模式(envelope: true)

参考 website/content/examples/20_output/envelope.md,启用信封只需一行配置:

const pokemon = Graffle.create({
  output: {
    envelope: true,
  },
})

const result = await pokemon.query.pokemons({ name: true })

console.log(result)

此时返回值被包装为信封结构,输出大致为:

{
  data: {
    pokemons: [
      { name: 'Pikachu' },
      { name: 'Charizard' },
      { name: 'Squirtle' },
      { name: 'Bulbasaur' },
      { name: 'Caterpie' },
      { name: 'Weedle' }
    ]
  },
  response: Response { /* HTTP 原始响应信息 */ }
}

从源码可见,envelope 支持三种写法(configuration.ts):

  • envelope: true / false:布尔开关;
  • envelope: { enabled: true }:长格式开关;
  • envelope: { enabled: true, errors: { execution: true, other: false } }:精细控制哪些错误类别进入信封的 errors 字段。

Standard GraphQL 模式(模拟传统 ExecutionResult)

参考 website/content/examples/20_output/standard-graphql.md,Graffle 内置了 Preset.traditionalGraphqlOutput 预设,用于近似传统 GraphQL ExecutionResult 输出:

import { Graffle, Preset } from 'graffle'

const graffle = Graffle
  .create({ output: Preset.traditionalGraphqlOutput })
  .transport({ url: `http://localhost:3000/graphql` })

// @ts-expect-error - intentionally invalid document: field 'query' doesn't exist on Query type
const result = await graffle.gql(`{ query { thisWillError } }`).$send()

console.log(result)

该示例同时演示了 Graffle 的静态校验能力:无效的 GraphQL 文档({ query { thisWillError } } 中 query 字段在 Query 类型上不存在)会在编译期被 @ts-expect-error 标注捕获。而对应的预设定义在源码中(configuration.ts):

export const traditionalGraphqlOutput = {
  defaults: { errorChannel: `throw` },
  envelope: { enabled: true, errors: { execution: true, other: false } },
  errors: { execution: `default`, other: `default` },
} satisfies Normalized

可见 Standard GraphQL 模式与默认输出的差异本质上是信封开关:开启 envelope 并把执行错误放入信封的 errors 字段,返回结构即贴近 ExecutionResult<{...}>。此外,配置系统还提供了 isOutputTraditionalGraphQLOutput 判定函数(configuration.ts),用于检测当前规范化配置是否满足"传统 GraphQL 输出"的特征。

返回错误模式(errorChannel: 'return')

参考 website/content/examples/20_output/return-error.md,若希望错误以返回值形式出现而非抛出,可配置:

const pokemon = Graffle
  .create({
    output: {
      envelope: false,
      defaults: {
        errorChannel: `return`,
      },
    },
  })
  .anyware(({ encode: _ }) => {
    throw new Error(`Something went wrong.`)
  })

const pokemons = await pokemon.query.pokemons({ name: true })

console.log(pokemons)

此时错误不再抛出,而是作为 ContextualError 之类的错误值返回(输出示例中可以看到携带 hookName: 'encode'、source: 'extension' 等上下文字段的错误对象)。这与默认行为形成鲜明对比:默认(errorChannel: 'throw')是抛出,而 'return' 是把错误放进返回值。

测试对默认行为的印证

仓库中的测试用例进一步证实了"默认是抛出错误"这一行为。在 src/client/methods/with_output.test.ts 中:

test('default is throws errors', async () => {
  await expect(g1.gql('').$send()).rejects.toThrowErrorMatchingInlineSnapshot(
    `[ContextualAggregateError]`,
  )
})
test('can return errors', async () => {
  const g2 = g1.with({ output: { defaults: { errorChannel: 'return' } } })
  const result = await g2.gql('').$send()
  expect(result).toMatchInlineSnapshot(`[ContextualAggregateError]`)
})

两个测试精确地反映了两种通道的语义差异:

  • 默认配置下,$send() 调用被拒绝(rejects),即错误被抛出;
  • 配置 output.defaults.errorChannel: 'return' 后,同一调用正常 resolve,错误作为返回值出现。

注意测试中错误对象均为 ContextualAggregateError——这是 Graffle 的上下文聚合错误类型,用于携带查询管道中各个阶段的上下文信息。

何时选择哪种输出模式

综合以上分析,可以给出如下实践建议:

  • 默认(裸数据 + 抛出):适合大多数业务场景。成功即得类型安全的数据,失败交给 try/catch,心智负担最小;
  • 信封模式(envelope: true):当需要同时拿到 data 与原始 response(状态码、请求头、原始响应体等)时使用,便于调试与自定义错误处理;
  • Standard GraphQL(Preset.traditionalGraphqlOutput):需要与既有 GraphQL 工具链、中间件或协议约定保持 ExecutionResult 兼容时使用;
  • 返回错误(errorChannel: 'return'):偏好函数式错误处理(显式检查返回值而非异常)的团队可选,且可通过 output.errors.execution / output.errors.other 对不同错误类别做细分控制。

值得注意的是,以上所有模式都建立在 Graffle 的配置规范化机制之上:无论传入的是布尔值、对象还是预设,最终都会归一为 configuration.ts 中定义的 Normalized 结构,保证运行时行为一致、可预测。

小结

本文围绕官方示例 output_default 与 示例文档,完整拆解了 Graffle 的默认输出行为:

  • 默认返回值是裸数据:envelope.enabled 默认为 false,查询成功时直接返回类型安全的纯数据数组;
  • 默认错误通道是抛出:defaults.errorChannel 默认为 'throw',errors.execution / errors.other 默认跟随该通道;
  • 配置结构清晰可扩展:output 配置由 defaults、envelope、errors 三部分组成,全部默认值可在 src/context/fragments/configuration/output/configuration.ts 中查证,相关行为由 src/client/methods/with_output.test.ts 中的测试用例验证;
  • 切换模式成本极低:通过 envelope: true、Preset.traditionalGraphqlOutput、defaults.errorChannel: 'return' 等配置即可切换到信封、Standard GraphQL 或返回错误等输出形态。

对刚接触 Graffle 的开发者来说,记住一句话即可:零配置的 Graffle,成功时给你干净的裸数据,失败时给你抛出异常——这正是它"极简"设计理念在输出层的体现。

登录后查看全文
graffle