我有一个 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/