react-apollo - Apollo 客户端:如何使用查询字符串查询休息端点?
问题描述
我正在使用 Apollo 调用从查询字符串中获取变量的休息端点:
/api/GetUserContainers?showActive=true&showSold=true
我无法弄清楚如何将变量传递给查询,因此它可以调用正确的 url。通过查看apollo-link-rest 文档和一些我认为我应该使用的问题,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',
})
在我看来,这些似乎是一个我想避免的非常老套的解决方案。
处理此查询字符串问题的推荐方法是什么?
解决方案
您不需要使用pathBuilder
简单查询字符串参数。您可以将参数直接作为变量useQuery
传递,然后path
使用{args.somearg}
语法直接传递给 teh。我看到的问题是您没有containerHistory
在查询别名中定义您用于查询 bu的变量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',
})
推荐阅读
- r - 如何在 R 中碱基对图的空白空间中添加图例?
- visual-studio-2019 - Visual Studio 2019 调试观察窗口
- javascript - 传入新道具时,如何将组件的状态重置为默认值?
- reactjs - React - UseState,UseRef..In Trouble
- python - 从 ul 类中获取所有元素并与文本文件进行比较(Python Selenium)
- php - 如何在 php 文件(wordpress)中显示自定义模板?
- sql-server - 优化海量数据查询
- svg - d3.js - 从边框到边框绘制箭头线
- java - 无法在另一个活动中将文本设置为文本视图
- mysql - 如何将 DateTimePicker 和 ComboBoxes 添加到 mysql 数据库,然后将其显示到 DataGridView