0
votes

In the Apollo Server documentation, it describes the behaviour of the default resolver, which is quite handy.

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:

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. 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!

1

1 Answers

1
votes

The default resolver is available through the graphql module:

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:

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