graphql: querying with dynamic filtering criteria

喜欢而已 提交于 2020-02-06 08:38:40

问题


I am trying to perform a query using the in operator where the criteria is based on values in an array. How can I perform the query below to take an array and base its in criteria off a variable array? I am using reactjs + gatsby.

... graphql`
      query pageHeader {
         .... there is another query in the real code above this line
         allContentInSites (filter: {slug: {in: ` + JSON.stringify(searchCriteria.map(item => item.value)) + ` }})  {
          edges {
            node {
              title,
              link
            }
          }
        }
      }'

I was initially thinking the sample code above would pass a json string object for the in criteria but this seems to break the page.


回答1:


This won't work in your page queries in Gatsby. The GraphQL query is evaluated and replaced with data statically prior to the code being executed.

You could potentially hook into the Node APIs provided by Gatsby to build this query during boot, though. You may be able to use onPreExtractQueries to create the query, or potentially use the graphql object provided by any of the node APIs in your gatsby-node.js to generate pages.




回答2:


if you would like to implement dynamic filtering criteria, you have couple options 1) You can use stringified json and send it as String and parse it on the server in resolver 2) You can use custom scalar graphql-type-json as argument type or implement your own custom scalar.

The big downsides of this is that you are loosing strongly typed features of GraphQL. You can also implement dynamic schema, but it is a little bit overkill and in general not a good practice. I would go for dynamic arguments only if it is the only option. Usually it can be rearanged so that you do not have to use dynamic arguments.

I am not sure if it is helpful as i am not familiar with gatsby specific issues with this, but this should work in general GraphQL schemas.



来源:https://stackoverflow.com/questions/51863657/graphql-querying-with-dynamic-filtering-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!