Vingtoft
Vingtoft

Reputation: 14616

GraphQL | How to implement conditional nesting?

Please consider the following GraphQL schema:

type User {
   id: ID!
   events: [Event]
}

type Event {
   id: ID!
   user: User!
   asset: Asset!
}

type Asset {
  id: ID
  price: Number!
  name: String!
}

GraphQL is a fantastic framework for fetching nested objects, but I'm struggling to understand how conditional nesting is implemented.

Example:

I want to retrieve all events for a specific user where asset.price is greater than x.

Or

I want to retrieve all events for an asset that belongs to a list of users [].

Question: Is conditional nesting a concept in GraphQL and how is it implemented?

Side note: I use AWS AppSync and resolvers are fetching data from AWS DynamoDB.

Upvotes: 1

Views: 1162

Answers (1)

cyberwombat
cyberwombat

Reputation: 40104

You can define a filter/condition on any GraphQL query such as:

query {
  users(permission: 'ADMIN') {
    ...
  }
}

The permission param is passed to your resolver (say DynamoDb VTL template, Lambda etc) to be handled however you want - to GQL this is just another parameter.

You can carry this concept into nested field by creating an events resolver and you'd then call it like this:

query {
  user(id: '123') {
    name
    events(minPrice: 200) {
      nodes: {
        id
        eventName
        eventDate
      }
    }
    dob
    ...
   }
}

In above case I am using a simple minPrice param but you could do more complex things such price ranges, even pass operators (eq, gt, ...). It's all irrelevant to GraphQL - all gets passed to the resolver.

How you implement that on backend depends on your setup. I use AppSync without Amplify and write my own VTL templates and build the DynamoDb request using the provided GQL fields.

Here is an SO post that shows how to create a date filter.

Upvotes: 1

Related Questions