gpt4 book ai didi

graphql - 如何将嵌套变量传递给 Apollo 中的 GraphQL 查询?

转载 作者:行者123 更新时间:2023-12-02 02:44:21 24 4
gpt4 key购买 nike

尝试将嵌套变量传递给 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 文档的有用片段,

All declared variables must be either scalars, enums, or input object types. So if you want to pass a complex object into a field, you need to know what input type that matches on the server.

您正确地将变量作为字符串传递,但随后尝试(也许成功,但我以前从未见过语法)在 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",
},
},
}
}
)

关于graphql - 如何将嵌套变量传递给 Apollo 中的 GraphQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63041747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com