graphql - 如何将嵌套变量传递给 Apollo 中的 GraphQL 查询?
问题描述
尝试将嵌套变量传递给 GraphQL 查询,但我的服务器只获取顶级变量 ( shopId
),其他一切都为空。
我试过了:
#1
const CALCULATE_PACKAGE_PRICE = gql`
query CalculatePackagePrice(
$shopId: String!
$address1: String
$zip: String
$city: String
$countryCode: String
) {
calculatePackagePrice(
where: {
shopId: $shopId
destination: {
address1: $address1
zip: $zip
city: $city
countryCode: $countryCode
}
}
) {
name
price
userErrors {
field
message
}
}
}
`
const [calculatePackagePrice, { loading, data }] = useLazyQuery(
CALCULATE_PACKAGE_PRICE,
{
variables: {
shopId: shopId,
destination: {
address1: "Example 123",
zip: "123",
city: "Test",
countryCode: "US",
},
},
}
)
和#2:
export function CALCULATE_PACKAGE_PRICE({ shopId, destination }) {
return gql`
query CalculatePackagePrice {
calculatePackagePrice(
where: {
shopId: "${shopId}"
destination: {
address1: "${destination.address1}"
zip: "${destination.zip}
city: "${destination.city}"
countryCode: "${destination.countryCode}"
}
}
) {
name
price
userErrors {
field
message
}
}
}
`
}
const [calculatePackagePrice, { loading, data }] = useLazyQuery(
CALCULATE_PACKAGE_PRICE({
shopId: shopId,
destination: {
address1: "Example 123",
zip: "123",
city: "Test",
countryCode: "US",
},
})
)
当我将变量内容硬编码到查询中时,它工作得很好。我做错了什么?
解决方案
这是来自 graphql 文档的有用片段,
所有声明的变量必须是标量、枚举或输入对象类型。因此,如果要将复杂对象传递到字段中,则需要知道服务器上匹配的输入类型。
您正确地将变量作为字符串传递,但随后尝试(也许成功,但我以前从未见过语法)在 gql 模板字符串中创建对象。相反,为目的地和地点创建一个输入类型。
input WhereInput {
shopId: String!
destination: DestinationInput!
}
input DestinationInput {
address1: String!
zip: String!
city: String!
countryCode: String!
}
然后更改客户端上的查询(并更新服务器定义),
const CALCULATE_PACKAGE_PRICE = gql`
query CalculatePackagePrice($where: WhereInput!) {
calculatePackagePrice(where: $where) {
name
price
userErrors {
field
message
}
}
}
`
然后传递变量,例如,
const [calculatePackagePrice, { loading, data }] = useLazyQuery(
CALCULATE_PACKAGE_PRICE,
{
variables: {
where: {
shopId,
destination: {
address1: "Example 123",
zip: "123",
city: "Test",
countryCode: "US",
},
},
}
}
)
推荐阅读
- sql - 如果出现空值,我可以使用什么 sql 语句?
- python - 有没有办法从python中的html标签中获取数据?
- javascript - Django Rest Framework 如何在另一种方法中调用变量?
- python-3.x - 如何修复 M1 Mac 上 CyLP 的导入错误?
- mongodb - 通过 REST API 将 MongoDB 与 React Native 连接
- javascript - 如何循环遍历对象数组并在下拉列表中显示
- c# - 如何获取 JObject 的根名称
- delphi - 访问 TWebRequest.Content 会在 ISAPI DLL 中引发 ERangeError 异常,但不会在控制台应用程序中引发
- r - 将存储在列表中的 data.frames 分成相等的部分
- google-sheets - 对手结果的查找公式