ZHANGYU.dev

October 14, 2023

GraphQL学习笔记

GraphQL5.1 min to read

什么是 GraphQL

GraphQL,是 Facebook 开源的一种 api 查询语言,对查询数据提供了一套完整的描述,客户端可以精准的获取需要的数据,而没有任何冗余

image

最基础的查询方式如上图,左边是请求,右边是响应,我希望获取todoList这个集合,集合里的每一个元素都包括_id,content,completed字段,服务端返回的数据就是我请求需要的数据,不会多也不会少

GraphQL 的基础概念——Query

type todo {    _id: ID!    content: String!    completed: Boolean!}

接着创建一个查询

type Query {    todoList: [todo]!}

GraphQL 中的数据类型

还可以自定义类型

搭建 GraphQL 服务器

了解了查询,就来创建一个 GraphQL 的服务器吧 我使用的是Apollo GraphQL,这是一个非常完整的 GraphQL 的实现,包括了客户端和服务端 node 服务器使用的是koa 现在就开始吧

首先创建一个项目,然后安装以下依赖

npm i -S apollo-server-koa graphql koa

根目录创建app.js文件

const Koa = require("koa");const { ApolloServer } = require("apollo-server-koa");const { gql } = require("apollo-server-koa");// 定义从服务器获取数据的graphql方法const typeDefs = gql`    type todo {        _id: ID!        content: String!        completed: Boolean!    }    type Query {        todoList: [todo]!    }`;const server = new ApolloServer({    // 使用gql标签和字符串定义的graphql的DocumentNode    typeDefs,    // 开启mock    mocks: true,});const app = new Koa();// applyMiddleware将graphql服务连接到koa框架server.applyMiddleware({ app });app.listen({ port: 4000 }, () =>    console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`));

接着运行node app.js,在http://localhost:4000/graphql就能看见apollo server提供的playground

查询

{    todoList {        _id        content        completed    }}

在左边输入上方的查询,右边就会出现 mock 的数据了

添加 resolvers

resolvers 是用于解析 typeDefs 查询的解析器,是一个键为type名,值为一个函数的映射 在app.js中添加resolvers

// ...// 创建一个数据const data = [    {        _id: "5ca16ed7c39e5a03d8ad3547",        content: "html5",        completed: false,    },    {        _id: "5ca16ee0c39e5a03d8ad3548",        content: "javascript",        completed: false,    },    {        _id: "5ca16ee5c39e5a03d8ad3549",        content: "css",        completed: false,    },];// resolvers// Query对应查询,todoList是一个函数,返回的是数据// 可以写异步函数,用于真实的数据库查询const resolvers = {    Query: {        todoList: () => data,    },};// 添加resolvers,取消掉mocksconst server = new ApolloServer({    typeDefs,    resolvers,});const app = new Koa();//...

再次查询,返回的结果就是data的数据了

GraphQL 的基础概念——Mutation

Mutation 可以对应 REST API 中的 CRUD,一个简单的mutation如下 在typeDefs中增加

type updateResponse {    success: Boolean!    todoList: [todo]!}type Mutation {    addTodo(content: String): updateResponse!}

这是一个 Mutation 的操作,增加一个todo项,返回一个updateResponse对象

在 playground 中执行

修改 resolvers

const resolvers = {    Query: {        todoList: () => data,    },    Mutation: {        addTodo: (_, { content }) => {            console.log(content);            data.push({                _id: Math.random()                    .toString(36)                    .substring(3),                content,                completed: false,            });            return { success: true, todoList: data };        },    },};

函数中具体的参数可查阅Resolver type signature

执行

mutation {    addTodo(content: "css") {        success        todoList {            _id            content            completed        }    }}

mutation表示这是一个mutation操作,操作名为addTodo,接收一个名为content类型为String的参数,返回的数据是successtodoList

在 nodejs 的控制台能看见 console 出来的参数

在客户端中使用 GraphQL

官方提供了包括reactreact-nativevueaugularnative-ios...等 在 creact-react-app 中使用

虽然官方提供了组件模式的QueryMutation组件,不过我在学习过程中,用的还是直接以 JS 写的方法模式,Client api 参考

create-react-app的项目中安装依赖

npm install apollo-boost react-apollo graphql --save

创建client.js,并在package.json中增加proxy

import ApolloClient from "apollo-boost";const Client = new ApolloClient();const getList = async () => {    return await Client.query({        query: gql`            {                todoList {                    _id                    content                    completed                }            }        `,    });};const add = async content => {    return await Client.mutate({        // 参数,content对应的下面的$content        variables: { content },        mutation: gql`            mutation add($content: String!) {                addTodo(content: $content) {                    success                    todoList {                        _id                        content                        completed                    }                }            }        `,    });};export { getList, add };

提供 IDE 支持

我使用的是 webstorm 是一款集成功能非常强大的 IDE,在 plugins 里搜索安装JS GraphQL

导出schema.json

webstrome 就会提供非常智能的 graphql 代码格式化和补全功能了

Demo

学习过程中写了 2 个 demo 客户端 服务端

不懂的地方依旧很多,文档是英文的又特别复杂,路漫漫其修远兮~ 不知何什么时候才能搭一个基于 graphql 的博客呢,wordpress 又慢又重,最主要的还是看不懂……