跳转到主要内容

标签(标签)

资源精选(342) Go开发(108) Go语言(103) Go(99) angular(82) LLM(75) 大语言模型(63) 人工智能(53) 前端开发(50) LangChain(43) golang(43) 机器学习(39) Go工程师(38) Go程序员(38) Go开发者(36) React(33) Go基础(29) Python(24) Vue(22) Web开发(20) Web技术(19) 精选资源(19) 深度学习(19) Java(18) ChatGTP(17) Cookie(16) android(16) 前端框架(13) JavaScript(13) Next.js(12) 安卓(11) 聊天机器人(10) typescript(10) 资料精选(10) NLP(10) 第三方Cookie(9) Redwoodjs(9) LLMOps(9) Go语言中级开发(9) 自然语言处理(9) PostgreSQL(9) 区块链(9) mlops(9) 安全(9) 全栈开发(8) ChatGPT(8) OpenAI(8) Linux(8) AI(8) GraphQL(8) iOS(8) 软件架构(7) Go语言高级开发(7) AWS(7) C++(7) 数据科学(7) whisper(6) Prisma(6) 隐私保护(6) RAG(6) JSON(6) DevOps(6) 数据可视化(6) wasm(6) 计算机视觉(6) 算法(6) Rust(6) 微服务(6) 隐私沙盒(5) FedCM(5) 语音识别(5) Angular开发(5) 快速应用开发(5) 提示工程(5) Agent(5) LLaMA(5) 低代码开发(5) Go测试(5) gorm(5) REST API(5) 推荐系统(5) WebAssembly(5) GameDev(5) CMS(5) CSS(5) machine-learning(5) 机器人(5) 游戏开发(5) Blockchain(5) Web安全(5) Kotlin(5) 低代码平台(5) 机器学习资源(5) Go资源(5) Nodejs(5) PHP(5) Swift(5) 智能体(4) devin(4) Blitz(4) javascript框架(4) Redwood(4) GDPR(4) 生成式人工智能(4) Angular16(4) Alpaca(4) 编程语言(4) SAML(4) JWT(4) JSON处理(4) Go并发(4) kafka(4) 移动开发(4) 移动应用(4) security(4) 隐私(4) spring-boot(4) 物联网(4) nextjs(4) 网络安全(4) API(4) Ruby(4) 信息安全(4) flutter(4) 专家智能体(3) Chrome(3) CHIPS(3) 3PC(3) SSE(3) 人工智能软件工程师(3) LLM Agent(3) Remix(3) Ubuntu(3) GPT4All(3) 软件开发(3) 问答系统(3) 开发工具(3) 最佳实践(3) RxJS(3) SSR(3) Node.js(3) Dolly(3) 移动应用开发(3) 低代码(3) IAM(3) Web框架(3) CORS(3) 基准测试(3) Go语言数据库开发(3) Oauth2(3) 并发(3) 主题(3) Theme(3) earth(3) nginx(3) 软件工程(3) azure(3) keycloak(3) 生产力工具(3) gpt3(3) 工作流(3) C(3) jupyter(3) 认证(3) prometheus(3) GAN(3) Spring(3) 逆向工程(3) 应用安全(3) Docker(3) Django(3) R(3) .NET(3) 大数据(3) Hacking(3) 渗透测试(3) C++资源(3) Mac(3) 微信小程序(3) Python资源(3) JHipster(3) 大型语言模型(2) 语言模型(2) 可穿戴设备(2) JDK(2) SQL(2) Apache(2) Hashicorp Vault(2) Spring Cloud Vault(2) Go语言Web开发(2) Go测试工程师(2) WebSocket(2) 容器化(2) AES(2) 加密(2) 输入验证(2) ORM(2) Fiber(2) Postgres(2) Gorilla Mux(2) Go数据库开发(2) 模块(2) 泛型(2) 指针(2) HTTP(2) PostgreSQL开发(2) Vault(2) K8s(2) Spring boot(2) R语言(2) 深度学习资源(2) 半监督学习(2) semi-supervised-learning(2) architecture(2) 普罗米修斯(2) 嵌入模型(2) productivity(2) 编码(2) Qt(2) 前端(2) Rust语言(2) NeRF(2) 神经辐射场(2) 元宇宙(2) CPP(2) 数据分析(2) spark(2) 流处理(2) Ionic(2) 人体姿势估计(2) human-pose-estimation(2) 视频处理(2) deep-learning(2) kotlin语言(2) kotlin开发(2) burp(2) Chatbot(2) npm(2) quantum(2) OCR(2) 游戏(2) game(2) 内容管理系统(2) MySQL(2) python-books(2) pentest(2) opengl(2) IDE(2) 漏洞赏金(2) Web(2) 知识图谱(2) PyTorch(2) 数据库(2) reverse-engineering(2) 数据工程(2) swift开发(2) rest(2) robotics(2) ios-animation(2) 知识蒸馏(2) 安卓开发(2) nestjs(2) solidity(2) 爬虫(2) 面试(2) 容器(2) C++精选(2) 人工智能资源(2) Machine Learning(2) 备忘单(2) 编程书籍(2) angular资源(2) 速查表(2) cheatsheets(2) SecOps(2) mlops资源(2) R资源(2) DDD(2) 架构设计模式(2) 量化(2) Hacking资源(2) 强化学习(2) flask(2) 设计(2) 性能(2) Sysadmin(2) 系统管理员(2) Java资源(2) 机器学习精选(2) android资源(2) android-UI(2) Mac资源(2) iOS资源(2) Vue资源(2) flutter资源(2) JavaScript精选(2) JavaScript资源(2) Rust开发(2) deeplearning(2) RAD(2)

使用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.

文章链接