Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL optional Query Arguments

I know you can set arguments in a schema to default values but is it possible to make the argument limit argument completely optional in my GraphQL Schema?

Right now it seems like when I hit this without specifying a limit I think that's why I get Int cannot represent non-integer value: undefined

const schema = buildSchema(`
  companies(limit: Int): [Company]
...)

enter image description here

I want to be able to skip the limit so that it gets all companies.

In JS, I call it like this:

query: `query { 
          companies(limit: ${limit}) {
 ...

but sometimes I don't want to specify a limit. So what is happening is the client is sending crafters(limit: undefined) and it's probably trying to convert that to Int. I'm not sure how to not send limit in and how to make that entire param optional.

(I also read that from the client I should be instead specifying the arguments as variables like query($limit: Int) { companies(limit: $limit) { I guess from my client, from JS? If so how would I send in my limit JS variable into that?

like image 463
PositiveGuy Avatar asked Oct 20 '20 00:10

PositiveGuy


Video Answer


1 Answers

Arguments in GraphQL are nullable (i.e. optional) by default. So if your type definition looks like this:

companies(limit: Int): [Company]

there is nothing else you need to do to make limit optional -- it already is. If you wanted to make limit required, you would make it non-nullable by appending a ! to the type like this:

companies(limit: Int!): [Company]

The errors you are seeing are unrelated to the type of the limit argument. The issue is with the query that you're sending, which based on the error messages, looks something like this:

query ($limit: Int){
  companies (limit: undefined) {
    # ...
  }
}

There's two issues here: One, you are defining a variable ($limit) that you never actually use inside the query (as indicated by the second error). Two, you are setting the limit to undefined, which isn't a valid literal in GraphQL.

Instead of using string interpolation, you should use variables to pass any dynamic values to your query. For example:

query ($limit: Int){
  companies (limit: $limit) {
    # ...
  }
}

If the variable is nullable (notice we used Int instead of Int!), then it can be omitted from the request entirely, effectively making the value of the argument undefined server-side. It's unclear how you're sending your requests to the server, but assuming you're not using some client library, you can check the documentation here for how to structure your request. Otherwise, check your library's documentation for how to correctly use variables with your query.

like image 55
Daniel Rearden Avatar answered Sep 24 '22 05:09

Daniel Rearden