Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert snake_case to camelCase field names in apollo-server-express

I'm new to GraphQL and Apollo Server, though I have scoured the documentation and Google for an answer. I'm using apollo-server-express to fetch data from a 3rd-party REST API. The REST API uses snake_case for its fields. Is there a simple way or Apollo Server canonical way to convert all resolved field names to camelCase?

I'd like to define my types using camel case like:

type SomeType {
  id: ID!
  createdTime: String
  updatedTime: String
}

but the REST API returns object like:

{
  "id": "1234"
  "created_time": "2018-12-14T17:57:39+00:00",
  "updated_time": "2018-12-14T17:57:39+00:00",
}

I'd really like to avoid manually normalizing field names in my resolvers i.e.

Query: {
    getObjects: () => new Promise((resolve, reject) => {
        apiClient.get('/path/to/resource', (err, response) => {
            if (err) {
                return reject(err)
            }

            resolve(normalizeFields(response.entities))
        })
    })
}

This approach seems error prone, given that I expect the amount of resolvers to be significant. It also feels like normalizing field names shouldn't be a responsibility of the resolver. Is there some feature of Apollo Server that will allow me to wholesale normalize field names or override the default field resolution?

like image 500
Joe Hawkins Avatar asked Jan 01 '23 12:01

Joe Hawkins


1 Answers

The solution proposed by @Webber is valid.

It is also possible to pass a fieldResolver parameter to the ApolloServer constructor to override the default field resolver provided by the graphql package.

const snakeCase = require('lodash.snakecase')

const snakeCaseFieldResolver = (source, args, contextValue, info) => {
  return source[snakeCase(info.fieldName)]
}

const server = new ApolloServer({ 
  fieldResolver: snakeCaseFieldResolver,
  resolvers,
  typeDefs
})

See the default field resolver in the graphql source code

like image 63
Joe Hawkins Avatar answered Jan 05 '23 14:01

Joe Hawkins