How to use Rest Link when there is a query of the form "foo.bar=["baz"]"?

Hello everyone,

I’m using Apollo Rest Link to call REST APIs inside my GraphQL queries.

My use case is this:

  1. Make a call to CKAN’s API to retrieve a list of datasets and some search facets (like tags, license_id, res_format). The API url looks something like this: https://demo.ckan.org/api/action/package_search?q=test&facet.field=[“tags”,“res_format”]&facet.limit=5
  2. Display the datasets on a page and the search facets in filter boxes.

My query looks like this

export const SEARCH_QUERY = gql`
  query search(
    $q: String
    $sort: String
    $rows: Int
    $start: Int
    $facetField: [String!]
    $facetMinCount: Int
    $facetLimit: Int
  ) {
    search(q: $q, sort: $sort, rows: $rows, start: $start, facet.field: $facetField facet.limit: $facetLimit)
      @rest(type: "Search", path: "package_search?{args}") {
      result {
        count
        results {
          name
          title
          notes
          tags
        }
        search_facets {
          tags {
            title
            items {
              name
              count
            }
          }
          res_format {
            title
            items {
              name
              count
            }
          }
        }
      }
    }
  }
`;

I parse the url from the browser and send the query parameters as variables for the query

await apolloClient.query({
    query: SEARCH_QUERY,
    variables,
  });

The problem is when I do this, I’m getting the error - GraphQLError: Syntax Error: Cannot parse the unexpected character “.”

I’m getting the error only when I add facet.limit, facet.field etc where there is a “.” How do I fix it?

I just found out that Apollo Rest Link uses (qs)[qs - npm] underneath and I changed my query to the one below and the error went away.

search(q: $q, sort: $sort, rows: $rows, start: $start, facet: {field: $facetField, limit: $facetLimit})

I’m still not getting the result I want but this is progress.

I’d recommend adjusting your path to be more specific about the structure it’s expecting, and use variable/argument names that are easier to use with GraphQL. In other words, try changing your search field and @rest call to something like:

...
search(q: $q, sort: $sort, rows: $rows, start: $start, facetField: $facetField facetLimit: $facetLimit)
  @rest(type: "Search", path: "package_search?q={args.q}&facet.field={args.facetField}&facet.limit={args.limit}") {
...

Your URL parameter names don’t have to match your GraphQL variables/arguments if you follow an approach like this.