在apollo-server-express 中将snake_case 转换为camelCase 字段名称 [英] Convert snake_case to camelCase field names in apollo-server-express

查看:15
本文介绍了在apollo-server-express 中将snake_case 转换为camelCase 字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 GraphQL 和 Apollo Server 的新手,尽管我已经搜索了文档和谷歌以获得答案.我正在使用 apollo-server-express 从 3rd-party REST API 获取数据.REST API 使用 snake_case 作为其字段.是否有一种简单的方法或 Apollo Server 的规范方法可以将所有解析的字段名称转换为驼峰命名法?

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

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 字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆