node.js - 如何 reshape GraphQL 响应?

标签 node.js graphql

我有一个 GraphQL 查询,如下所示:

type Query {
    getProfile(userId: ID!): UserProfile
}

type UserProfile {
    userId: ID!
    name: String!
    email: String!
    street: String!
    city: String
    country: String!
    postal: String!
}
但是,似乎我只能使用这样的别名修改来自查询的响应:
query {
    getProfile(userId: "12345") {
        userId
        name
        email
        streetName: street
        city
        country
        postalCode: postal
    }
}
我想 reshape 响应,这样我就不必通过对象的数据映射器来处理响应。例如,我可能想 reshape 响应,使其看起来像这样:
{
    userId: 12345,
    name: "John",
    email: "john@smith.com",
    address: {
        streetName: "my street name",
        city: "WA",
        country: "US",
        postalCode: "54321"
    }
}
在这种情况下,我添加了一个额外的级别 address在回应中。我必须有一个 type在 GraphQL 服务器上专门为此形状声明的?如果我无权这样做,例如,它是第三方 GraphQL API,该怎么办?
在使用常规 REST API 时,我仍然面临着必须在 UI 中重新映射响应的相同问题。在我的情况下,仅使用别名更改字段名称通常是不够的。
如何构建我的 GraphQL 查询以 reshape 响应以返回不同的形状?

最佳答案

我认为您可以将架构改进为:

type UserProfile {
    userId: ID!
    name: String!
    email: String!
    address: Address
}

type Address {
    street: String!
    city: String
    country: String!
    postal: String!
}

然后您可以为用户数据使用不同的解析器,如果您愿意,还可以使用地址信息

关于node.js - 如何 reshape GraphQL 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63475640/

相关文章:

类型为 "image"的 GraphQL 错误字段 "File"必须选择子字段。你的意思是 "image { ... }"吗?

node.js - nodejs 中的永远是什么?

javascript - 如何锁定由nodejs中的多个异步方法共享的对象?

javascript - graphqljs - 如何获取文件名和错误行

javascript - GraphQL js 文件上传

javascript - 为什么我的 Graphql 查询返回 null?

flutter - 错误: Couldn't resolve the package 'gql_code_builder' from repository layer

node.js - MongoDB 获得餐厅剩余座位

node.js - node.js 垃圾收集的时机

sql - 将 SQL 查询转换为 Sequelize ORM 返回不需要的结果