首页 > 解决方案 > 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',
})

在我看来,这些似乎是一个我想避免的非常老套的解决方案。

处理此查询字符串问题的推荐方法是什么?

标签: react-apolloapollo-clientapollo-link-rest

解决方案


您不需要使用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',
})

推荐阅读