Table of Contents

Hasura GraphQL + NextJS Part 2

Hasura GraphQL + NextJS Part 2

Author

Utsav Ojha
Utsav OjhaSoftware Engineer

Date

Oct 31, 2022
Hasura GraphQL + NextJS Part 2

Book a Discovery Call

Recaptcha Failed.

In this part, we will look atĀ QueriesĀ (fetching data),Ā MutationsĀ (writing data) andĀ SubscriptionsĀ (watching data) using Hasura GraphQL. Let's go! šŸ

Check theĀ GraphiQL playgroundĀ to play with theĀ Todo APIĀ built with Hasura GraphQL (you will need to sign up for a Hasura account).

  • Tools like GraphiQL make GraphQL APIs really easy to use and integrate APIs in your app without requiring external documentation tools.
  • GraphiQL is a tool built by Facebook, (pronounced "graphical") that makes it easy to explore any GraphQL API.
  • When you work with a GraphQL API in a project you will almost always use a tool like GraphiQL to explore and test your GraphQL queries.

First, here's a look at the data models and how they are linked to each other.

Data models

Exploring Queries (fetching data) in GraphiQL Playground 🐶

  • As you can see, the 3 models are linked to each other. Let's try toĀ fetch different slices of data from our overall 'graph'.

  • Let's fetch some slices of data now (following screenshots have the GraphQL query in the left window and the response on the right window):

First, let's fetchĀ usernames like so:

GraphiQL queries example

Second, let's fetch users and their todos, like so:

GraphiQL queries example 2

Now lets fetch data with some parameters or arguments, think about this RESTful endpointĀ GET /api/todos?limit=Ā whereĀ limit=3Ā is theĀ query-param, in GraphQL we can do:

GraphiQL queries example 3

In the above ā˜ļø example or incase we are using any arguments, GraphQL servers will provide a list of arguments that can be used in () next to specific fields.

Since we have used Hasura to build our GraphQL API we also getĀ filter,Ā sortĀ andĀ paginationĀ arguments. Incase you have a custom GraphQL API, you might have access to different arguments for specific fields.

Finally, let's take a look at Multiple arguments on multiple fields. Lets fetch 5 most recent todos for 1 user, like so:

GraphiQL queries example 4

In the above ā˜ļø example, the query can be translated into simple english asĀ Fetch users (with limit 1), and their todos (ordered by descending creation time, and limited to 5).

Last and most important, we need to make our queries reusable, so we need to be able to pass queries dynamically. This can be achieved like:

GraphiQL queries example 5

In the above ā˜ļø example, we are dynamically adding arguments or parameters to our queries to multiple specific fields. Let's translate our query to simple english asĀ Fetch users (with limit $user_limit), and their todos (ordered by descending creation time and limited by $todo_limit).

We have also defined the type our arguments will be, we can learn more about the different data typesĀ here

What we learned from the above ā˜ļø code snippets:

Exploring Mutations (writing data) in GraphiQL Playground šŸ‘¾

Now, let's get started with seeing how we can use GraphQL to "write" data. GraphQL mutations are types of GraphQL queries that may result in the state of your backend "mutating" or changing, just like typicalĀ 'POST',Ā 'PUT',Ā 'PATCH',Ā 'DELETE'Ā APIs.

Basic Mutations

Since we're using Hasura for our GraphQL API, we get mutations forĀ inserts,Ā updatesĀ orĀ deletesĀ that we can use in our app. If we are using a custom GraphQL API, created by a backend team not by Hasura then we might have access to different mutations and these might behave differently.

First, let's create a todo (this is in context of our todo API), like:

GraphiQL queries example 7

From the above ā˜ļø example, we can see that, the todo we want to create i.eĀ insertĀ is passed as argument to theĀ insert_todosĀ mutation, but the 'fields' we are returning are responsible for the shape of our response.

GraphiQL queries mutations

When inserting data, we almost always want to capture data from user input or user action. So, the data we are passing is going to be dynamic, we can achieve this like:

GraphiQL queries example 8

From the above ā˜ļø example, we can see that the argumentĀ $todoĀ is of typeĀ todo_insert_inputĀ and this is defined in the schema, incase of custom GraphQL API which is not created by a backend team, they will define these input types and our mutation argument must conform to these rules, shape of the object we are passing.

We will take a look at theĀ updateĀ andĀ deleteĀ actions a bit later in this series.

What we learned from the above ā˜ļø code snippets:

  • Make basic GraphQL mutations.
  • Can pass dynamic arguments/data to mutations with query variables.

Exploring Subscriptions (subscribing, listening for changing data) in GraphiQL Playground šŸ“¶

The GraphQL specification allows for something called subscriptions that are like GraphQL queries but instead of returning data in one read, you get data pushed from the server.

A strong use case for subscriptions

This is useful for your app to subscribe to "events" or "live results" from the backend, but while allowing you to control the "shape" of the event from your app.

GraphQL subscriptions are a critical component of adding realtime or reactive features to your apps easily. GraphQL clients and servers that support subscriptions are great because they allow you to build great experiences without having to deal with websocket code! 🤯

Let's set up a subscription to check users online, each time the data changes on the server, it will push the changes to the client.

GraphiQL queries example 10

How does this GraphQL subscription work? šŸ› 

A GraphQL subscription is a subscription query string sent to a websocket endpoint. And whenever data changes on the backend, new data is pushed over websockets from the server to the client. That can't happen over a POST endpoint, because a simple HTTP endpoint would just return the response and the connection would close.

What we learned from the above ā˜ļø code snippet:

  • Make GraphQL subscriptions.

We are now ready to setup our Hasura backend, which we will implement in the next part!

Related Articles

Dive deep into our research and insights. In our articles and blogs, we explore topics on design, how it relates to development, and impact of various trends to businesses.