我正在使用Apollo调用从查询字符串中获取变量的其余端点:
/api/GetUserContainers?showActive=true&showSold=true
我在弄清楚如何将变量传递给查询时遇到麻烦,因此它可以调用正确的url。通过查看apollo-link-rest docs和一些问题,我认为我应该使用pathBuilder
,但这没有记录,因此我无法使其正常工作。
到目前为止,我已经定义了这样的查询:
getUserContainersQuery: gql`
query RESTgetUserContainers($showActive: Boolean, $showSold: Boolean, $pathBuilder: any) {
containerHistory @rest(type: "ContainerHistoryResponse", pathBuilder: $pathBuilder) {
active @type(name: "UserContainer") {
...ContainerFragment
}
sold @type(name: "UserContainer") {
...ContainerFragment
}
}
}
${ContainerFragment}
`
并在我的组件中调用它,不起作用:
import queryString from 'query-string'
// ...
const { data } = useQuery(getUserContainersQuery, {
variables: {
showActive: true,
showSold: false,
pathBuilder: () => `/api/GetUserContainers?${queryString.stringify(params)}`,
},
fetchPolicy: 'cache-and-network',
})
使它起作用的唯一方法是将完整构造的路径从组件传递到查询:
// query definition
getUserContainersQuery: gql`
query RESTgetUserContainers($pathString: String) {
containerHistory @rest(type: "ContainerHistoryResponse", path: $pathString) { // <-- pass path here, instead of pathBuilder
// same response as above
}
}
`
// component
const params = {
showActive: true,
showSold: false,
}
const { data } = useQuery(getUserContainersQuery, {
variables: {
pathString: `/api/GetUserContainers?${queryString.stringify(params)}`,
},
fetchPolicy: 'cache-and-network',
})
在我看来,这些似乎是一个非常棘手的解决方案,我想避免。
处理此查询字符串问题的推荐方法是什么?
答案 0 :(得分:1)
对于简单的查询字符串参数,您不需要使用pathBuilder
。您可以将参数直接作为变量传递给useQuery
,然后使用path
语法直接传递给{args.somearg}
。我看到的问题是,您尚未仅在查询别名containerHistory
中定义用于查询RESTgetUserQueries
的变量。如果已更新,则应如下所示:
// query definition
getUserContainersQuery: gql`
query RESTgetUserContainers($showActive: Boolean, $showSold: Boolean) {
// pass the variables to the query
containerHistory(showActive:$showActive, showSold:$showSold) @rest(type: "ContainerHistoryResponse", path:"/api/GetUserContainers?showActive={args.showActive}&showSold={args.showTrue}") {
//.. some expected reponse
}
}
`
// component
const params = {
showActive: true,
showSold: false,
}
const { data } = useQuery(getUserContainersQuery, {
variables: {
showActive,
showSold
},
fetchPolicy: 'cache-and-network',
})