如何在Pothos GraphQL中创建无返回类型的Query字段?
在Pothos GraphQL中创建无返回类型的Query字段
GraphQL规范里不存在真正的“无返回类型”,所有字段都必须声明返回类型。要实现类似“不返回实际内容”的效果,有两种常用方案:
方案一:用Boolean类型标记执行状态
将字段类型设为Boolean,在resolve函数里返回固定值(比如true),仅用来标识操作完成:
builder.queryType({ fields: (t) => ({ exchange: t.field({ args: { code: t.arg.string(), }, // 指定返回类型为Boolean type: 'Boolean', resolve: (parent, { code }) => { console.log(code); // 返回true表示执行完成 return true; }, }), }), });
方案二:自定义Void标量类型
如果追求语义更明确,可以自定义一个Void标量,专门用来表示无返回内容的场景:
1. 定义Void标量
const VoidScalar = builder.scalarType('Void', { serialize: () => null, parseValue: () => null, parseLiteral: () => null, });
2. 将字段类型指定为Void标量
builder.queryType({ fields: (t) => ({ exchange: t.field({ args: { code: t.arg.string(), }, type: VoidScalar, resolve: (parent, { code }) => { console.log(code); // 返回null匹配Void标量的定义 return null; }, }), }), });
关键注意点
- 不能省略
type属性,否则Pothos会自动推断类型,可能引发报错或不符合预期的行为。 - 无论哪种方案,resolve函数都必须返回符合类型定义的值,否则GraphQL会抛出执行错误。
内容的提问来源于stack exchange,提问作者NGI
相关产品推荐
相关产品推荐

