Apollo Server v4能否为整个GraphQL类型指定解析器?
在Apollo Server v4中为Thing类型设置全局解析器的实现方法
Apollo Server v4完全支持为特定GraphQL类型定义全局解析器,刚好能解决你遇到的重复代码和遗漏风险问题——不用在每个包含Thing的字段解析器里重复处理,只要定义一次Thing类型的解析逻辑,所有返回Thing(或Thing数组)的字段都会自动应用这个逻辑。
具体实现方式
假设你的数据源返回的是简化格式(比如仅包含type的对象,甚至直接是type字符串),你可以为Thing类型编写全局解析器,自动将这些简化数据转换成符合Schema定义的完整Thing对象:
示例1:上层返回带type的对象
如果A.things和B.things返回的是包含type字段的对象数组,只需为Thing的icon字段单独编写解析逻辑:
const resolvers = { // 为Thing类型定义全局字段解析器 Thing: { icon: (parent) => { // 根据type映射对应icon的逻辑 const iconMap = { 'post': 'icon-post', 'comment': 'icon-comment', 'user': 'icon-user' }; return iconMap[parent.type] || 'icon-default'; } }, A: { things: () => { // 只需返回包含type的对象,无需处理icon return [{ type: 'post' }, { type: 'comment' }]; } }, B: { things: () => { return [{ type: 'user' }]; } } };
示例2:上层直接返回type字符串
如果A.things和B.things返回的是纯type字符串数组,你可以为Thing类型本身编写解析函数,将字符串转换成完整对象:
const resolvers = { // 为Thing类型定义全局解析函数,处理原始输入 Thing: (parent) => { const iconMap = { 'post': 'icon-post', 'comment': 'icon-comment', 'user': 'icon-user' }; return { type: parent, icon: iconMap[parent] || 'icon-default' }; }, A: { things: () => ['post', 'comment'] }, B: { things: () => ['user'] } };
效果说明
不管是现有A.things、B.things,还是后续新增的C.things等字段,只要它们返回的格式能被Thing类型解析器处理,Apollo都会自动调用该解析器生成完整的Thing对象,彻底避免重复代码和遗漏风险。
内容的提问来源于stack exchange,提问作者Tamlyn
相关产品推荐
相关产品推荐

