0

Is there a package/methodology for dynamically creating a graphql query on the client-side? For example, let's pretend that I have the following query

query { 
  foo {
    a
    b
    c {
      d {
        e
        f
      }
    g
  }
}

I want to allow the user to pick/choose what data fields get returned from that query. In other words, if they do not want a field back, I would omit it from the query. * This is because some fields contain a very large amount of data and it would be better to avoid bandwidth issues if it can be avoided.

Do I have to build the query by hand (ugh) or is there a javascript tool out there that people use for this situation?

I saw this but it looks like it's no longer maintained and has some issues noted in the issues tab: https://github.com/codemeasandwich/graphql-query-builder

ekjcfn3902039
  • 1,673
  • 3
  • 29
  • 54

1 Answers1

2

You might have to build the query yourself (it's just a string, after all), in which case making use of the Builder pattern might help, since it seems like you have a complex set of parameters determining what should be included in the query.

Have you looked at these SO answers? Do these get at what you need?

GraphQL dynamic query building

React Apollo dynamically create query from state (if you're using React/Apollo)

One thing to keep in mind is that you lose some caching and security benefits by using dynamic, rather than static, client queries.

I would also suggest alerting your users that selecting certain fields will incur an expensive query; at the very least, paginate that data so that you're not returning such a large volume of it all at once.

diekunstderfuge
  • 521
  • 1
  • 7
  • 15
  • Hi, thanks! I don't think I want to use fragments as there could be 100s of possible results returned for a single query. I like the idea of the dynamic one in the second link but I'm not sure that would account for recursively nested objects. I already have paging so I am not sending back more data than is needed. – ekjcfn3902039 Jul 12 '19 at 13:43