跳转到主要内容

使用GraphQL编写数据和查询API可以加快软件开发过程。与REST API相比,使用GraphQL可以得到您想要的东西,后者为您提供了一个可能导致数据传输浪费的完整数据集。使用GraphQL技术查询API意味着我们终于可以告别过度获取了。

将任何软件应用程序与GraphQL绑定将提高应用程序的性能,因为您只选择需要的字段。在本教程中,您将学习如何使用Apollo客户端将GraphQL与Angular框架绑定。AWS RDS将成为我们的Postgres数据库,我们将在其上部署Hasura。Hasura GraphQL引擎将使我们能够快速连接到我们的GraphQL API。为了高效地开发我们的GraphQL API,我们将使用Hasura来完成以下工作;

  • 创建一个表。
  • 设置外键。
  • 查询响应缓存。

为了更好地理解这个概念,我们的Angular应用程序将使用突变创建新闻文章,并提取文章,以便将它们注入用户界面。

TABLE OF CONTENTS

  1. 在AWS RDS Postgres上部署Hasura。
  2. 数据库建模。
  3. 使用Apollo将GraphQL与Angular绑定。
  4. 转变
  5. 查询
  6. 使用Hasura GraphQL引擎的查询响应缓存。
  7. 结论

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引擎通过连接到Postgres数据库并为您提供快速实时的GraphQL API来提高可访问性,从而使软件开发更加容易。要将Hasura连接到Amazon RDS Postgres,我们将从创建数据库开始,然后在创建Postgres URL时获取所需的数据库凭据。

Creating an AWS account

我将给出一个关于如何创建AWS RDS Postgres数据库的指南。有关Hasura部署文档的更多信息,请查看此链接。

亚马逊网络服务为亚马逊RDS提供了一个免费层,帮助新的AWS客户免费在云中开始使用托管数据库服务。出于验证目的,在创建AWS账户时,它将进行1美元的信用卡验证交易,1美元将被退还。

继续并在此处创建AWS帐户。在帐户选项中选择根用户帐户类型。

创建数据库并构建Amazon RDS Postgres URL

要在Postgres数据库上部署Hasura,您需要一个Postgres URL。我们将首先创建AWS RDS Postgres数据库,然后使用我们的数据库凭据创建Postgres URL。

成功登录后,在搜索栏上搜索AWS RDS。一旦你在列表中找到它,点击它就可以访问它。一旦你选择了亚马逊RDS,你会在仪表板上看到创建数据库按钮。点击它,开始创建亚马逊RDS Postgres数据库。


在引擎选项中,选择Postgres作为引擎类型。
配置设置时,选择一个DB实例标识符作为数据库的名称,postgres默认为Master用户名。您可以选择编写自己的密码,也可以允许亚马逊自动为您生成密码。


如果您允许amazon为您创建数据库密码,则在您创建数据库后,密码将显示在数据库凭据中。


启用公共访问,选择现有VPC安全组或添加新组。安全组将充当实例的虚拟防火墙,以控制入站流量。


完成后,单击创建按钮。


允许从Hasura Cloud连接到您的数据库

单击您选择的活动VPC安全组。


单击蓝色突出显示的安全组。


现在点击下面的编辑入站规则按钮。


部署部分

登录Hasura云并创建一个新项目。创建项目后,它将自动将您重定向到项目面板。

在项目面板中,您可以看到下一步需要的Hasura Cloud IP。
下一步是单击添加规则按钮,输入在上一步中复制的Hasura IP地址,并将端口设置为5432。
添加规则后,单击“保存规则”按钮。


正在创建数据库连接URL

数据库连接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.

文章链接