我有一个 GraphQL 查询,如下所示:
type Query {
getProfile(userId: ID!): UserProfile
}
type UserProfile {
userId: ID!
name: String!
email: String!
street: String!
city: String
country: String!
postal: String!
}
Run Code Online (Sandbox Code Playgroud)
但是,似乎我仅限于使用如下别名修改查询的响应:
query {
getProfile(userId: "12345") {
userId
name
email
streetName: street
city
country
postalCode: postal
}
}
Run Code Online (Sandbox Code Playgroud)
我想重塑响应,这样我就不必将响应通过我的对象的数据映射器。例如,我可能想重塑响应,使其看起来像这样:
{
userId: 12345,
name: "John",
email: "john@smith.com",
address: {
streetName: "my street name",
city: "WA",
country: "US",
postalCode: "54321"
}
}
Run Code Online (Sandbox Code Playgroud)
address在这种情况下,我在响应中添加了额外的级别。我必须type在 GraphQL 服务器上专门针对此形状声明吗?如果我无权执行此操作(例如,它是第三方 GraphQL API)怎么办?
感觉我仍然面临着同样的问题,即在使用常规 REST API 时必须在 UI 中重新映射响应。在我的情况下,仅使用别名更改字段名称通常是不够的。
如何构建 GraphQL 查询来重塑响应以不同的形状返回?
小智 -2
我认为你可以将你的模式改进为:
type UserProfile {
userId: ID!
name: String!
email: String!
address: Address
}
type Address {
street: String!
city: String
country: String!
postal: String!
}
Run Code Online (Sandbox Code Playgroud)
然后,如果您愿意,您可以为用户数据和地址信息使用不同的解析器
| 归档时间: |
|
| 查看次数: |
1213 次 |
| 最近记录: |