问题描述
我是GraphQL和Apollo Server的新手,尽管我已经搜索了文档和Google来寻找答案.我正在使用apollo-server-express从第三方REST API中获取数据.REST API的字段使用snake_case.是否有一种简单的方法或Apollo Server规范方法将所有已解析的字段名称转换为camelCase?
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
}
但是REST API返回的对象如下:
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))
})
})
}
鉴于我希望解析器的数量很多,因此这种方法似乎容易出错.还感觉规范化字段名称不应该由解析程序负责.Apollo Server是否有一些功能可以让我批发标准化字段名称或覆盖默认的字段分辨率?
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?
推荐答案
我想您可以在将结果返回给客户端之前,将normalizeFields函数放置在graphql中间件中. Graphql中间件.
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.
这篇关于在apollo-server-express中将snake_case转换为camelCase字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!