Skip to content

Requests

Vinicius Reif Biavatti edited this page Jan 20, 2020 · 2 revisions

Access the GraphiQL in any browser to start to make queries. In our case, we can access this URL: localhost:3000/graphql. To begining, let's create our library, our authors, and our books. After to create them, we will link the books with the libraries and start to make the queries.

To create our first library, we have to say to the GraphQL that we will make a mutation, and call the mutation function with the parameters of the new object we will create. It is required to define the data to return, otherwise the GraphQL will throw an exception. To define it, just put the data we want inside the {} characteres after the function call:

mutation {
  createLibrary(name: "New York Public Library") {
    id
  }
}

With this code, we will create a new library with name "New York Public Library". Check that we will request by the id of the library created.

The return will be:

{
  "data": {
    "createLibrary": {
      "id": "0"
    }
  }
}

Now, we can create the author and the book with the id of the author we created:

mutation {
  createAuthor(firstname: "Dan", lastname: "Brown") {
    id
  }
  createBook(title: "The Da Vinci Code", number: 1, authorId: 0) {
    id
  }
}

The returned data is:

{
  "data": {
    "createAuthor": {
      "id": "0"
    },
    "createBook": {
      "id": "0"
    }
  }
}

Let's link the book in our library calling our linkBook() function:

mutation {
  linkBook(libraryId: 0, bookId: 0) {
    name
  }
}

And now, lets make a full query to get the libraries, books and authors:

query {
  libraries {
    id,
    name,
    books {
      id,
      title,
      number,
      author {
        firstname,
        lastname
      }
    }
  }
}

The result is:

{
  "data": {
    "libraries": [
      {
        "id": "0",
        "name": "New York Public Library",
        "books": [
          {
            "id": "0",
            "title": "The Da Vinci Code",
            "number": 1,
            "author": {
              "firstname": "Dan",
              "lastname": "Brown"
            }
          }
        ]
      }
    ]
  }
}

To finish this tutorial, let's make a filtered request to GraphQL and check the result:

query {
  library(libraryId: 1) {
    name,
    books {
        title
    }
  }
}

The result is:

{
  "data": {
    "library": {
      "name": "New York Public Library",
      "books": [
        {
          "title": "The Da Vinci Code"
        }
      ]
    }
  }
}

Congratulations! We finished our tutorial. Thanks for follow this tutorial and good luck for your purposes! Bye!

Clone this wiki locally