tags

The Ultimate Guide To Developing an Angular App With GraphQL, Amazon Rds and Hasura

04 July, 2022 | 10 min read

Writing data and querying an API using GraphQL can make your software development process faster. Using GraphQL you get exactly what you asked for, compared to a REST API which gives you a whole data set that could lead to data transfer waste. Querying APIs with GraphQL technology means we can finally bid farewell to over-fetching.

Binding any software application with GraphQL will improve your app’s performance as you only select fields you need. In this tutorial, you will learn how to bind GraphQL with Angular framework using the Apollo Client. AWS RDS will be our Postgres database and we will deploy Hasura on it. Hasura GraphQL engine will enable us to connect to our GraphQl API swiftly. To develop our GraphQL API efficiently we will use Hasura to do the following;

  • Create a table.
  • Set a foreign key.
  • Query response caching.

To grasp the concept better, our Angular app will be creating news articles using mutations and fetching articles so that they can be injected into the user interface.

TABLE OF CONTENTS

1. Deploying Hasura on AWS RDS Postgres.

2. Database modeling.

3. Binding GraphQL with Angular using Apollo.

4. Mutation

5. Querying

6. Query Response caching using Hasura GraphQL engine.

7. Conclusion

TL;DR: You will learn how to integrate GraphQL with Angular using the Apollo client. And also get to deploy Hasura on AWS RDS Postgres database and use Hasura’s query response caching feature.

Prerequisites and Requirements

This tutorial will simply explain GraphQL concepts so you don’t need to have a lot of knowledge on GraphQL. You will use the following technologies in this tutorial.

● Node.js

● Angular framework.

● Hasura GraphQL engine.

● Apollo GraphQL Client.

● Amazon RDS as the Postgres database.

Deploying Hasura on AWS RDS

Hasura GraphQL engine improves accessibility by connecting to your Postgres database and offering you a swift real-time GraphQL API making software development much easier. To connect Hasura to Amazon RDS Postgres we will start off by creating a database and then move on to getting the database credentials required when creating a Postgres URL.

Creating an AWS account

I will give a guideline on how to create an AWS RDS Postgres database. For more on the Hasura deploying documentation check this link.

The Amazon web services provide a free Tier for the amazon RDS which helps new AWS customers get started with a managed database service in the cloud for free. For verification purposes it will carry out a $1 transaction for credit card validation when creating the AWS account and the $1 will be returned.

Go ahead and create the AWS account here. Choose the root user account type on the account options.

Creating a database and constructing the Amazon RDS Postgres URL

To deploy Hasura on a Postgres database you will need a Postgres URL. We will first create the AWS RDS Postgres database and then go on to creating the Postgres URL using our database credentials.

After you have successfully logged in, search for AWS RDS on the search bar. Once you find it in the list click on it to access it. Once you have chosen the Amazon RDS, on the dashboard you will see the create a database button. Click on it to start creating the Amazon RDS Postgres database.

In Engine options, select Postgres as your Engine type.

When configuring the settings choose a DB instance identifier as the name for your database and postgres is the Master user name by default. You can choose to write your own password or allow amazon to automatically generate one for you.

If you have allowed amazon to create the database password for you, the password will be shown in the database credentials after you have created the database.

Enable Public access and choose an existing VPC security group or add a new group. The security group will function as a virtual firewall for your instance in order to control inbound traffic.

When you are done click on the create button.

Allowing connections to your Database from Hasura Cloud

Click on the active VPC security group you chose.

Click on the security group highlighted in blue.

Now click on the edit inbound rules button below.

The deploying part

Login to Hasura cloud and create a new project. After creating the project, it will automatically redirect you to the project dashboard.

In the project dashboard, you can see the Hasura Cloud IP, which you will need in the next step.

The next step is to click on the add rule button and enter the Hasura IP address you copied in the previous step and set the port to 5432.

After adding the rule click on the save rules button.

Creating your database connection URL

Contents of database connection URL

  1. user-name: The default user name is postgres but if you have specified and have a separate database the user name will be your name.
  2. Password: Here, use the password you chose when creating the password.
  3. Public ip: Your endpoint is the public IP. You can find it under the connectivity and security tab.
  4. postgres-port: When creating the rules we set the port to 5432 as it is the default port.
  5. db is postgres by default.

This is the structure of our URL below.

postgresql://<user-name>:<password>@<public-ip>:<postgres-port>/<db>

Now let's finish the task by inserting the URL. Add the database connection string in the “Database URL” and click “Connect Database”.

And that’s it!

Database Design and structure

Before we hop onto GraphQL schema creation let's take a look at the database structure. Our articles table will have these fields article_Id, author, title, story. The articles_Id field will be our primary key. The Users table will have two fields which are category and author.

Let us create a table using the Hasura GraphQL engine. To create a table in Hasura GraphQL engine click on the Data tab and select create table.

With Hasura we can create a foreign key and it will automatically suggest a suitable relationship between the fields looking at table details. The author field is a foreign key as it points to the primary key of the Article table. To create a foreign key, scroll down and click on create a foreign key.

Setting up Angular

To set up or install the angular framework, you must have node.js installed on your computer. You can download node.js from here.

The following command lets you install angular using your favorite command line.

npm install -g @angular/cli

Creating a project

After installing angular you can go ahead and type in the following command to create a new project.

ng new news-app

Binding GraphQL with Angular

https://www.apollographql.com/docs/intro/platform/

Apollo is a GraphQL client, its task is to handle network requests and inject data into the web user interface. With a large developer ecosystem, it is easy to find tutorials and documentation compared to its rival Relay. Since Apollo supports any GraphQL server and GraphQL schema, we will integrate it with the Angular framework.

Installing Apollo

In order to use Apollo Client for Angular, we need to add a few packages to our project. Execute the following command within the Angular project directory:

npm install @apollo/client graphql

Import the following angular modules

The ApolloModule provides entrance to Apollo client features in our web app while the HttpLinkModule is used to fetch data in Angular.

import { BrowserModule } from '@angular/platform-browser';

import { FormsModule } from '@angular/forms';

import { NgModule } from '@angular/core'

import { HttpClientModule  } from "@angular/common/http";

import { APOLLO_OPTIONS } from "apollo-angular";

import { HttpLink } from 'apollo-angular/http';

import { InMemoryCache } from '@apollo/client/core';

 

We will enable in-memory caching by adding the caching property and passing an instance of InMemoryCache. In order to connect to our GraphQL endpoint, we use the create method which takes in a configuration object. This object contains a uri property, which will be your GraphQL endpoint.

imports: [

    BrowserModule,

    AppRoutingModule,

    FormsModule,

  HttpClientModule

  ],

  providers: [{

    provide: APOLLO_OPTIONS,

    useFactory: (httpLink: HttpLink) => {

      return {

        cache: new InMemoryCache(),

        link:  httpLink.create({

        uri: '[URL]',

            headers: {

              Authorization: `Bearer ${localStorage.getItem('token')}`

            }

        })

      };

    },

    deps: [HttpLink]

  }]

 

Let's start binding

There are two ways we can create GraphQL schemas. The first way is to express GraphQL schemas as Javascript objects based on the graphql-js library and the SDL will be auto-generated from source code. The second way is to describe our GraphQL schemas in SDL and link up business logic using the Apollo graphql-tools library. For this tutorial, we will use the first approach.

Creating a news article

“If queries are GET requests, mutations can be seen as POST/PATCH/PUT/DELETE requests (although really they are synchronized versions of queries)”~Amaury Martiny

The process of writing data in GraphQL is called Mutation. This procedure can involve creating data or deleting data. We will use mutation to create a news article by adding details to these fields title, author, story. The mutation endpoint on the server is shown below.

type Mutation {

createArticle(title: String!, author: String!, story: String):Article

}

Now lets bind and access the mutation endpoint using the Apollo client.

import { Component, OnInit } from '@angular/core';

import { Apollo } from 'apollo-angular';

import gql from 'graphql-tag';

@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.scss']

})

export class AppComponent implements OnInit {

  data: any;

  constructor(private apollo: Apollo) { }

  ngOnInit() {

    this.apollo.mutate({

      mutation: gql`mutation {

        createArticle(title:"Why Use GraphQL", author: "Hasura", story: "Graphql deletes overfetching in many ways..")

        {

          article_Id

        }

      }`

    }).subscribe(data => {

      //successfully created an article.

    });

  }

}

In this call, we only asked for the article_Id field and the server will give us this field only from the data object. When using the Apollo mutate method we do not have to explicitly handle the results, the results will be automatically integrated into the cache.

Fetching news posts

A query simply describes the data that you want to fetch from a GraphQL server. Mutations and queries both have similar structures the main difference is that they have different operation names. We will fetch our articles using the Apollo watchquery method. To achieve this task we need to start off by parsing our query into a GraphQL document using the gql tag from apollo/client/core library. The GetArticles query will fetch the article title, author, and story.

//  use the gql tag to parse our query string into a query document

const GET_ARTICLES = gql`

  query GetArticles {

    articles {

    title

    author

    story

    }

  }

`;


Inside the Articlescomponent class Create a result object which contains a boolean loading. After fetching articles the boolean will be set to false. The Apollo Watchquery method can continue setting the boolean to false if you specify and set its parameters as notifyOnNetworkStatusChange to true. When the query has been accomplished it contains a data object with articles.

class ArticlesComponent implements OnInit, OnDestroy {

  loading: boolean;

  articles: any;


  private querySubscription: Subscription;


  constructor(private apollo: Apollo) {}


  ngOnInit() {

    this.querySubscription = this.apollo.watchQuery<any>({

      query: GET_ARTICLES

    })

      .valueChanges

      .subscribe(({ data, loading }) => {

        this.loading = loading;

        this.articles = data.articles;

      });

  }


  ngOnDestroy() {

    this.querySubscription.unsubscribe();

  }

}

Improving query response performance

To improve query response performance for our GetArticles query which will be frequently used we will enable the query response caching in Hasura. To do so we will simply add @cached in our query directive.

query GetArticles @cached(ttl: 240) {

  articles {

    title

    author

    story

  }

}

The ttl argument specifies the lifetime of the query response. The maximum you can set is 5 minutes. Once our response is cached fruitfully the HTTP response will include a X-Hasura-TTLheader .

In conclusion

Thanks for reading! Those were the basic concepts to start off with building an angular app with GraphQL. I hope you have learned a lot from this tutorial and now ready to advance onto major topics such as caching and testing GraphQL API.

“There is no real ending. It’s just the place where you stop the story.”~Frank Herbert

Hasura Con
Check out the product announcements from HasuraCon’22
View Recordings
Hasura Con
The Hasura User Conference | June 28 - 30, 2022
New Product Announcements
View Recordings

Hasura

Hasura

Instant GraphQL API on all your data. Get Authorization, Caching, Performance and Monitoring benefits for all new and existing GraphQL APIs.

Read More

Monthly product updates in your inbox. No spam.
Loading...
News letter