Apollo GraphQL 笔记

GraphQL 是Facebook的 API 的查询语言,也是使用现有数据完成这些查询的运行时。GraphQL 为 API 中的数据提供了完整且易于理解的描述,使客户端能够准确地询问他们需要什么,此特性使 API 随着时间的推移更容易发展,并提供了强大的开发人员工具。

Apollo GraphQL是一套基于GraphQL的API组件,支持多个编程语言。

本文介绍用Apollo GraphQL搭建一套简单的前后端通讯案例,本文后端使用基于ts-node的node.js,前端基于angular。

后端

由于typescript在node.js中使用广泛,本文所用的后端语言为typescript。
首先init一个node.js工程目录,安装graphql server所需要的库:

npm install apollo-server graphql

这里写一个query books的示例,简单的graphql代码如下:

import {ApolloServer, gql} from 'apollo-server'

const typeDefs = gql`
  # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.

  # This "Book" type defines the queryable fields for every book in our data source.
  type Book {
    title: String
    author: String
    price: Float    
  }

  # The "Query" type is special: it lists all of the available queries that
  # clients can execute, along with the return type for each. In this
  # case, the "books" query returns an array of zero or more Books (defined above).
  type Query {
    books: [Book]
  }
`;

const books = [
  {
    title: 'The Awakening',
    author: 'Kate Chopin',
  },
  {
    title: 'City of Glass',
    author: 'Paul Auster',
  },
];

const resolvers = {
  Query: {
    books: () => {
      console.log('Resolve books');
      return books;
    },
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  csrfPrevention: true,
  cache: 'bounded',
});

// The `listen` method launches a web server.
server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});

前端

参考:https://apollo-angular.com/docs
目前最新的apollo-angular版本为V3,对应的angular版本是13,所以用ng先init一个angular13的工程。
然后在工程中安装apollo client需要的库,安装方式有两种:
一种使用ng

ng add apollo-angular

一种用npm手动安装

npm install apollo-angular @apollo/client graphql

如果用ng安装可以看到app目录下有文件graphql.module.ts自动生成,里面可以修改uri地址为后端部署的地址:

const uri = 'https://localhost:4000'; // <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
  return {
    link: httpLink.create({uri}),
    cache: new InMemoryCache(),
  };
}

@NgModule({
  exports: [ApolloModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule {}

这里注意如果query失败,可以试着将https改成http。
前端新建一个component用来显示graphql的内容。
html:

<div *ngIf="loading">
  Loading...
</div>
<div *ngIf="error">
  Error :(
</div>
<div *ngIf="books">
  <div *ngFor="let book of books">
    <p>{{ book.author }}: {{ book.title }}</p>
  </div>
</div>

ts:

import { Component, OnInit } from '@angular/core';
import {Apollo, gql} from "apollo-angular";

const booksQuery = gql`
  query GetBooks {
    books {
      title
      author
    }
  }
`;

@Component({
  selector: 'app-books-panel',
  templateUrl: './books-panel.component.html',
  styleUrls: ['./books-panel.component.scss']
})
export class BooksPanelComponent implements OnInit {

  books: any[] = [];
  loading = true;
  error: any;

  constructor(private apollo: Apollo) { }

  ngOnInit(): void {
    this.apollo
    .watchQuery({
      query: booksQuery,
    })
    .valueChanges.subscribe((result: any) => {
      this.books = result?.data?.books;
      this.loading = result.loading;
      this.error = result.error;
    });
  }

}

运行并启动浏览器,可以看到成功运行:
image

后端输出:
image

posted @   Asp1rant  阅读(149)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示