简体   繁体   English

Apollo GraphQL:扩展而不是覆盖默认解析器行为

[英]Apollo GraphQL: Augment instead of overriding default resolver behaviour

In the Apollo Server documentation, it describes the behaviour of the default resolver , which is quite handy. 在Apollo Server文档中,它描述了默认解析器的行为,这非常方便。

I also gathered from somewhere else (another SO question if I recall), that you can override the default resolver function with your own, by passing a fieldResolver function into the options for the apollo-server instance: 我还从其他地方(如果还记得,还有另一个SO问题)收集到了,您可以通过将fieldResolver函数传递给apollo-server实例的选项来覆盖自己的默认resolver函数:

const server = new ApolloServer({ typeDefs, resolvers,
  fieldResolver: function (source, args, context, info) {
    console.log("Field resolver triggered!")
    return null;
  }
});

What I would like to do is augment the default behaviour, rather than overriding it. 我想做的是增加默认行为,而不是覆盖默认行为。 Specifically, I am integrating with a REST API that returns fields in snake_case, whereas my schema is attempting to follow the advised convention of using camelCase for field names. 具体来说,我正在与一个REST API集成,该API将返回snake_case中的字段,而我的架构正尝试遵循使用camelCase作为字段名称的建议约定。 I would like to wrap this field name conversion around the default resolver behaviour, rather than having to re-write it. 我想将此字段名称转换包装在默认解析器行为的周围,而不必重新编写。

Alternatively, if somebody can point me to the source location for the default resolver implementation, I'd be happy enough to take that and adapt it either! 另外,如果有人可以将我指向默认解析器实现的源位置,我很乐意接受它并对其进行调整!

The default resolver is available through the graphql module: 可通过graphql模块获得默认解析器:

const { defaultFieldResolver } = require('graphql')

However, converting a field from snake case to camel case can be done without calling the default resolver: 但是,可以将字段从蛇格转换为驼峰格,而无需调用默认解析器:

someField: (parent) => parent.some_field

If you want to create a reusable resolver function, you can do something like: 如果要创建可重用的解析器功能,可以执行以下操作:

const camelCaseResolver = (parent, args, ctx, info) => {
  return parent[_.snakeCase(info.fieldName)]
}

Or better yet, extract the logic into a schema directive : 或者更好的是,将逻辑提取到schema指令中

class SnakeCaseDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    field.resolve = async function (parent, args, ctx, info) {
      return parent[_.snakeCase(info.fieldName)]
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM