Passing Multiple Arguments to GraphQL Query
Asked Answered
B

3

14

First thing

Appreciate this may be a bit of a stupid question, but I'm working with GraphQL having come from the RDF/Linked Data world and having a lot of trouble getting my head around how I would return a set. Essentially I want something where I could select, let's say a list of Characters (using the examples from the GraphQL docs) via their id. In SPARQL I'd be using the VALUES clause and then binding, something like:

VALUES { <http://uri/id-1> <http://uri/id-2> <http://uri/id-3> }

I'd assume something like this would be what I'd want (pseudocode)

{
  human(id: ["1", "2", "3", "4", "5"]) {
    name
    height
  }
}

Aliases kind of do what I want, but I don't want to have to specify in advance or manually what the different named return values are - I want to say in my code pass a list of IDs:

[1 2 3 4 5]

...and have a query that could accept that array of IDs and return me results in a predictable non-scalar shape as per the pseudo-query above.

Second thing

I'm also assuming that it's in fact not possible to have a query resolve to either a Human or [Human] - that it has to be one or the other? No biggie if so, I'd just settle for the latter... but I think I'm just generally quite confused over this now.

Buseck answered 27/9, 2017 at 10:52 Comment(2)
For example, am I thinking about this wrong, and I should define say a Slice type where I can define multiple arguments to chop up a hypothetical list into ranges? Even so, that kind of feels sub optimal for processing lists of resources.Buseck
And ideally I'd like to avoid having a string input like "[1 2 3 4 5]" so I don't have to worry about parsing, although I suppose that's a last ditch option.Buseck
R
15

First you need to extend you query by adding a "humans":

extend type Query {
  humans(listId: [String!]): [Human!]
  human(id: ObjID!): Human
}

Second - write a resolver for it.

Query: {
  humans(root, {listId}, { Human }) {
    return Human.fillAllByListId(listId);
  },
  ...
},

List of IDs could be passed as follows: pass list of IDs

Ratliff answered 27/9, 2017 at 13:1 Comment(0)
A
7

You can use GraphQL Aliases

{
    first: human(id: "1") {
        name
        height
    }
    second: human(id: "2") {
        name
        height
    }
}
Attendance answered 14/10, 2021 at 12:25 Comment(1)
works without adjusting the serverside, perfect!Confectioner
Q
3

Whit Hasura you can do like this (IDK if that working only on Hasura)

query getConfigurationList($ids: [String!]!) {
    configuration (where: {id:{_in: $ids}}){
        id
        value
    }
}

Here is the docs

Quintain answered 11/6, 2019 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.