4

Kickstart GraphQL Backends with Hasura

 2 years ago
source link: https://blog.bitsrc.io/kickstart-graphql-backends-with-hasura-23c7b9a5d854
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Using it in Practice: Let’s Build an App

In this section, let’s see how we can build a GraphQL application using Hasura. This application will maintain a collection of Pokemons 😀.

01. Create a project in the Hasura cloud.

1*t333qaKIeDIisYA1L219rQ.png?q=20
kickstart-graphql-backends-with-hasura-23c7b9a5d854
Hasura Project

We will be using a Postgres Database for this demo application.

Hasura allows you to connect to your own Postgres DB or connect your Heroku account, creating a Postgres DB on Heroku.

In addition, Hasura provides a decent UI for database management.

Here you can make the schemas and table for your application.

Connecting Heroku and create Hasura

02. Moving into GraphQL playground.

Now that we have created our database on Heroku via Hasura. Let’s move towards the Hasura Dashboard, where you can find the GraphQL playground.

Here you can see that the schemas are automatically generated with the Queries and Mutation for the table you created in Postgres DB.

Hasura GraphQL Playground

In this application, we will be using several features provided by Hasura. They are Events and Actions, which will allow you to connect to external data sources or trigger events whenever some changes are introduced to your Postgres DB.

1*CQIqoE4uHKSNROwtuHz7kw.png?q=20
kickstart-graphql-backends-with-hasura-23c7b9a5d854
Demo application Architecture

As you can see in the above diagram, I’m using some External services like Pokemon API and Serverless functions (using Netlify f

unctions) for fetching and saving data.

03 Create the frontend application.

Now let’s create our frontend application which will consume the GraphQL endpoints in Hasura. We will be using create-react-app with URQL, which is a highly customizable and versatile GraphQL client.

Use the following command to create the React application.

npx create-react-app hasura-pokemon

04. Installing dependencies and connect the application.

Inside the project root, execute the following command.

yarn add urq graphql l@astrajs/collections antd node-fetch

This command will install the libraries for the URQL GraphQL client and some dependencies for our Netlify functions.

Now that the dependencies are installed, let’s connect to our Hasura GraphQL server. To do that, add the following code snippet inside the index.js file.

import { createClient, Provider } from 'urql';const client = createClient({
url: process.env.REACT_APP_HASURA_URL,
fetchOptions: () => {
return {
headers: {
'content-type': 'application/json',
'x-hasura-admin-secret': process.env.REACT_APP_HASURA_SECRET
},
};
},
});ReactDOM.render(
<Provider value={client}>
<App />
</Provider>,
document.getElementById('root')
);

Note that we have used some environmental variables to pass the Hasura Secret and Hasura GraphQL endpoint URL.

You can find these two keys from the Hasura project settings.

Next, you will need to pass the Hasura secret code through the header called “x-hasura-admin-secret”.

05. Moving through Queries.

Now that the basic structure is complete let’s move on to querying the GraphQL through URQL.

First, let’s consume the Query at the PokemonList.jsx file.

The above Query and Mutations are taken from the Hasura Dashboard. Hasura allows real-time subscriptions as well. So if you need to listen to the changes that occur to the Pokemons, you have to change the GraphQL Query from type Query to Subscription like below.

import { useSubscription } from 'urql';const PokemonsSubscription = `
subscription PokemonsSubscription{
Pokemons_Pokemon {
id
name
power
description
}
}`;const [res] = useSubscription({ query: PokemonsSubscription}, (messages = [], response) => {
return [response.PokemonsSubscription, ...messages];
});

Next, let’s move toward the pokemon creation in PokemonForm.jsx file.

06. Creating Actions in Hasura

After that, we can start creating Actions. For this, we will be using the Pokemon API integration, which will be an external REST API.

Hasura’s actions will make a POST request, So to get the data from this endpoint, we will pass it through a Netlify function, creating a GET request to the Pokemon API.

You will have to create a Custom Query or a Mutation from the Hasura Dashboard to create this Action. Since we need to fetch data from the REST endpoint, let’s make a Query for this.

Here, the Action/Query will have a return object structure as mentioned below: Query and ResultOutput type.

type ResultOutput {
count: String!
next: String!
previous: String!
results: String!
}type Query {
getPokemons: ResultOutput
}
1*mo5ERYWlzFFJdDZena4PFQ.png?q=20
kickstart-graphql-backends-with-hasura-23c7b9a5d854
Hasura Action getPokemon

This Action can be executed as a regular GraphQL query. So if we run the Query getPokemon, it will call the Netlify function, making a GET request to Pokemon REST API.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK