GraphQL-- 使用Apollo Server搭建Node服务端
一、关于Apollo Server
Apollo Server是一种使用JS创建GraphQL服务端的一个方案。它的兼容性比较好,可以很好地和GraphQL客户端进行兼容。同时它可以
- 独立作为服务端进行
- 以插件的形式与现有的NodeJS 服务端程序进行兼容
- 可以作为一个GraphQL的数据网关。
官网地址:https://www.apollographql.com/docs/apollo-server/
二、搭建Apollo GraphQL Server
1) 和搭建Node Server类似。具体命令如下
npm init --yes
npm i apollo-server graphql
- apollo-server 是Apollo Server的核心库
- graphql是用于构建GraphQL Schema和执行查询的核心库
2) 使用Babel配置ES6
npm i @babel/cli @babel/core @babel/node @babel/preset-env
3) 创建GraphQL Schema
- 创建graphtype
import { gql } from "apollo-server"; export default gql` type Book { title: String author: String } `;
- 创建query graphtype
import { gql } from "apollo-server"; export default gql` type Query { books: [Book] } `;
import bookTypes from "./book.types"; import queries from "./queries"; export default [bookTypes, queries];
- 创建resolver
import dataset from "../dataset"; // dataset即为数据源 const Query = { books: () => dataset.books, }; const resolvers = { Query, }; export default resolvers;
- 创建schema
import { makeExecutableSchema } from "apollo-server"; import typeDefs from "@graphtypes";// 这是配置了alias,引用的是graph type的导出,即export default [bookTypes, queries];
import resolvers from "@resolver";
export default makeExecutableSchema({ typeDefs, resolvers, });
3) 配置启动脚本
import "module-alias/register"; import { ApolloServer } from "apollo-server"; import schema from "@schema"; import plugins from "@plugins"; const port = 8080; const server = new ApolloServer({ schema, plugins, formatError: (err) => { // 设置响应的错误信息进行格式化处理 return err.message; }, }); server.listen({ port }).then((serverInfo) => { console.log("===================================="); console.log(`Apollo GraphQL Server are listening at ${serverInfo.url}`); console.log("===================================="); });
三、配置package.json
"scripts": { "dev": "nodemon --exec babel-node index.js", "test": "echo \"Error: no test specified\" && exit 1" },
四、启动和测试
运行命令:
npm run dev
项目会运行在http://localhost:8080
因为Apollo GraphQL Server将PlayGround整合进去了,所以可以直接使用playground进行调试
项目代码可查看:
https://gitee.com/KingGang/apollo-graphql-server-management
本文原创作者:古道瘦西风,转载请注明原文链接:https://www.cnblogs.com/kingkangstudy/p/12913739.html