David542
David542

Reputation: 110163

How are nodes and edges connected in GraphQL?

I am using https://arrows.app/ to create a basic network:

enter image description here

And the resulting GraphQL it creates is:

type Person {
  Name: Dante Alighieri
  wroteBook: Book @relationship(type: "WROTE", direction: OUT)
}

type Book {
  Title: The Inferno
  personWrote: Person @relationship(type: "WROTE", direction: IN)
  personReviewed: Person @relationship(type: "REVIEWED", direction: IN)
  personRead: Person @relationship(type: "READ", direction: IN)
}

type Person {
  Name: Harold Bloom
  reviewedBook: Book @relationship(type: "REVIEWED", direction: OUT)
  reviewedBook: Book @relationship(type: "REVIEWED", direction: OUT)
}
...

How do we know in GraphQL that these two relationships are 'linked'?

type Person {
  Name: Dante Alighieri
  wroteBook: Book @relationship(type: "WROTE", direction: OUT)
}
type Book {
  Title: The Inferno
  personWrote: Person @relationship(type: "WROTE", direction: IN)
}

Does sequential ordering in GraphQL imply a relationship, as there is no ID or mention of 'The Inferno' in the 'Person[@Name=Dante Alighieri].wroteBook' entry. How do we know, for example, that it doesn't refer to a later entry, such as:

type Book {
  Title: The Tempest
  personWrote: Person @relationship(type: "WROTE", direction: IN)
}

Upvotes: 2

Views: 288

Answers (1)

Peter Malik
Peter Malik

Reputation: 463

One thing you could do is define your schema the following way:

type Book{
 id: ID!
 title: String!
 personWrote: Person!
}

The way GraphQL knows how to map these two is by creating a resolver for the Book type in your resolvers:

   export default {
    Query: {
        ...
    },
    Mutation: {
        ...
    },
    Book: {
        personWrote: async (parent, __, context) => {
            const bookId = parent.id

            //fetch the author who wrote the book from your database
            const bookAuthor = Authors.findBookById(id)

            return bookAuthor
        }
    }
}

This way, GraphQL is now expecting an Author type and can further have access to all its fields.

Upvotes: 1

Related Questions