21

Had a good search, but can't seem to find anything for this. Is there a way in GraphQL to only access the first item in an array?

Something like:

query {
  allDBItems {
    edges {
      node {
        exampleArray([0])
      }
    }
  }
}

2 Answers 2

15

No, GraphQL does not provide any syntax for manipulating the request, outside of conditionally including/excluding fields using the @skip and @include directives.

The GraphQL service you are querying may support a way to limit the result set for a field to a specific length by providing an argument on the field like limit, first or last. However, it's up to the server to include these fields as part of the service's schema and to provide the logic to implement them. Check your API's documentation to see if these fields are supported.

Any manipulations of the response have to be done client-side. There is an experimental graphql-lodash library that lets you do this right inside your queries -- but at the end of the day, the data is still being transformed client-side.

Sign up to request clarification or add additional context in comments.

1 Comment

I think this approach will undermine the GraphQL ability to statically verify upfront if an operation is valid before deployment.
-1

NOT this way - there is no such 'client only' syntax.

General rule 'ask for what you need' requires an explicit expression when passing [named] parameters (variables).

Just tell your API what you need - pass a limit (and index?) parameter - sth recognizable for your API [resolvers].

Without that you can just use only the first of all returned array elements - suitable only for small datasets.

Read graphql docs about pagination.

2 Comments

Thank you for taking the time to respond. So you can't put a limit on the size of the returned arrays? As in, you can only retrieve the full arrays? I have some very large arrays and need only the first item in each. I'm guessing you can't use (first:x) on an individual array.
You can pass variables to tell API how many records you need - resolver should use this parameter for SQL LIMIT (f.e.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.