user1518183
user1518183

Reputation: 4771

Bidirectional fetching in GraphQL

I have the following GraphQL schema:

interface Node {
  id: ID!
}

type User : Node {
  id: ID!
  name: String!
  tasks: [Task]
}

type Task : Node {
  id: ID!
  day: Int!
  description: String!
}

type Viewer {
  users: [User]
}

type Query {
  viewer: Viewer
}

Basically, every user can have a list of tasks. The problem occurs when I need to fetch a list of all tasks to get a response like this:

tasks: [{
  day: 1,
  user: {
    name: "John"
  }
}, {
  day: 2,
  user: {
    name: "Jane"
  }
}]

How should I edit my schema to allow fetching like that?

Upvotes: 1

Views: 1853

Answers (1)

Petr Bela
Petr Bela

Reputation: 8741

To be able to fetch a list of all tasks, add it as a property on the Viewer

type Viewer {
  users: [User]
  tasks: [Task]
}

and add users field to Task:

type Task : Node {
  id: ID!
  day: Int!
  description: String!
  users: [User]
}

With the updated schema, you can query for a list of all users as well as tasks:

{
  viewer {
    users {  // all users
      name
      tasks {  // user's tasks
        description
      }
    }
    tasks {  // all tasks
      day
      users {  // task's users
        name
      }
    }
  }
}

Also, you should be using pagination instead fetching all tasks (or users) at once. If you're planning to use your GraphQL server with Relay, define your users/tasks not as a List, but as a Connection with edges. See https://facebook.github.io/relay/docs/graphql-connections.html#content

Upvotes: 2

Related Questions