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

孤街醉人 提交于 2021-02-04 19:01:47

问题


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?


回答1:


I'd imagine you can place the normalizeFields function inside a graphql middleware right before it returns the results to the client side. Something like so Graphql Middleware.

A middleware would be a good centralized location to put your logic, so you don't need to add the function each time you have a new resolver.




回答2:


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



来源:https://stackoverflow.com/questions/53881054/convert-snake-case-to-camelcase-field-names-in-apollo-server-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!