• graphql 项目搭建(二)


    一、Express基本框架

    1.新建一个文件夹gql-server

      vscode 打开项目,在终端下输入yarn init -y 生成package.json 包(如果没安装yarn ,npm也一样,安装 yarn (npm install -g yarn))

    2.安装基本所需要的包 (npm 是 npm install)

    • express包 yarn add express express-graphql
    • graphql包 yarn add graphql graphql-playground apollo-server-express graphql-server-express graphql-tools  
    • typescript包和nodemon 服务包 yarn add typescript ts-node nodemon 
    • node包 yarn add @types/node @types/body-parser
    • 其它包 yarn add  require-text graphql-playground-middleware-express@1.1.2

    3.新建文件夹src,并且添加文件index.ts和server.ts

    • 在跟目录下添加tsconfig.json并且添加代码如下:
      • {
            "compilerOptions": {
                "module": "commonjs",
                "moduleResolution": "node",
                "target": "es6",
                "noImplicitAny": false,
                "sourceMap": true,
                "outDir": "dist",
                "lib": [
                    "es5",
                    "es6",
                    "dom",
                    "esnext.asynciterable"
                ],
            },
            "include": [
                "./src/**/*"
            ],
            "exclude": [
                "views",
                "static",
                "node_modules"
            ],
            "baseUrl": "types",
            "typeRoots": [
                "types"
            ]
        }
    • 添加server.ts的代码如下:
      •  1 import * as express from 'express';
         2 
         3 class Server {
         4     public app: express.Application;
         5     constructor() {
         6         this.app = express();
         7         this.routes()
         8     }
         9 
        10     private routes(): void {
        11         this.app.get('/', (req, res) => {
        12             res.send("Hello world")
        13         });
        14     }
        15 }
        16 
        17 export default new Server().app;
    • 在index.ts添加启动服务代码如下:
      •  1 import App from './server';
         2 
         3 class Index {
         4 
         5     private PORT: number = 8080
         6 
         7     constructor() {
         8 
         9     }
        10 
        11     Start() {
        12         App.listen(this.PORT,()=>{
        13             console.log('Now browse to http://localhost:8080');
        14         });
        15     }
        16 }
        17 
        18 new Index().Start()
    • 在package.json里添加启动运行脚本:
      • "scripts": {
            "start": "nodemon --exec ./node_modules/.bin/ts-node -- ./src/index.ts"
          }
    • 整个package.json代码如下:
      • {
          "name": "gql-server",
          "version": "1.0.0",
          "main": "index.js",
          "license": "MIT",
          "dependencies": {
            "apollo-server-express": "^1.3.4",
            "express": "^4.16.3",
            "express-graphql": "^0.6.12",
            "graphql": "^0.13.2",
            "graphql-playground": "^1.3.17",
            "graphql-server-express": "^1.3.4",
            "graphql-tools": "^2.24.0",
            "nodemon": "^1.17.3",
            "ts-node": "^5.0.1",
            "typescript": "^2.8.1"
          },
          "scripts": {
            "start": "nodemon --exec ./node_modules/.bin/ts-node -- ./src/index.ts"
          }
        }

     基本框架以搭成,在当前目录gql-server,终端下输入:yarn start,应该看到如下代码:

    基本的一个基于express 使用typescript的服务框架以完成了。项目结构如下图:

     

     在浏览器中输入http://localhost:8080/ 可以看到Hello world 输出。

     二、实现基本的Graphql server

    • 在src文件夹下添加base.gql文件代码如下:
    • # 查询
      type Query {
          dummy: Boolean
      }
      
      # 变更
      type Mutation {
          dummy: Boolean
      }
    • 在src文件夹下添加schema.ts文件基本意思导入base.gql然后通过grapqhl-tools生成schema,代码如下:
    • import { makeExecutableSchema } from 'graphql-tools';
      var requireText = require('require-text');
      var Base = requireText('./base.gql', require);
      
      //基础信息
      var typeDefs = [Base];
      
      const schema = makeExecutableSchema({
        typeDefs: typeDefs,
      })
      
      
      export default schema;
    • 修改server.ts 基本意思使用apollo-server-express来加载graphql,然后通过中间件graphql-playground-middleware-express来创建一个显示界面代码如下:
    • import * as express from 'express';
      const { graphqlExpress, graphiqlExpress } = require('apollo-server-express');
      const expressPlayground = require('graphql-playground-middleware-express').default;
      var bodyParser = require('body-parser');
      
      import schema from './schema';
      
      class Server {
          public app: express.Application;
          constructor() {
              this.app = express();
              this.routes()
          }
      
          private routes(): void {
              this.app.use('/graphql',bodyParser.json(), graphqlExpress({ schema }));
              this.app.get('/playground', expressPlayground({ endpoint: '/graphql' }));
          }
      }
      
      export default new Server().app;
    • 重新运行yarn start ,在浏览器中打开 http://localhost:8080/playground 可以看到如下页面:
    • 基本的Graphql框架已经可以使用最基本的语法了,输入query{ dummy } 或添加操作 mutation { dummy } 当然它返回的是null

     三、实现Graphql server Scham的resolve方案

    • 在src目录下添加user文件并添加user.gql和resolver.ts
    • user/user.gql添加如下代码:
    • type User{
          id:String
          name:String
          passwrod:String
      }
      
      
      extend type Query {
          # 查找所有用户
          getUsers: [User]
      }
      
      extend type Mutation {
          # 创建用户|修改用户
          saveUser(user:inputUser):User
      }
      
      input inputUser{
          id:String
          name:String
          passwrod:String
      }
    • 修改schema.ts 文件,将user.gql 导入进来全部代码如下
    • import { makeExecutableSchema } from 'graphql-tools';
      var requireText = require('require-text');
      var Base = requireText('./base.gql', require);
      var User = requireText('./user/user.gql', require);

      //基础信息
      var typeDefs = [Base];
      typeDefs=typeDefs.concat(User);

      const schema = makeExecutableSchema({
      typeDefs: typeDefs,
      })


      export default schema;
    • 刷新页面应该可以看到如下界面:查询显示为null
    • user/resolver.ts 添加代码如下:
    • export class User {
          constructor() {
      
          }
          //实现user.gql里面extend type Query的方法
          static Query: any = {
              getUsers(parent, { }, context) {
                  return [
                      { id: 1, name: "lslgg", passwrod: "123456" },
                      { id: 1, name: "lslgg", passwrod: "123456" }
                  ];
              }
          }
          //实现user.gql里面extend type Mutation的方法
          static Mutation: any = {
              saveUser(parent, { user }, context) {
                  return user;
              }
          }
      
      }
    • 将user/resolver.ts 导入到src下resolvers.ts里面代码如下:
    •  1 import { User } from "./user/resolver";
       2 
       3 export default {
       4     Query:{
       5         ...User.Query
       6     },
       7     Mutation:{
       8         ...User.Mutation
       9     },
      10 };
    • 将src/resolvers.ts导入到 schema.ts 里面代码如下:
    •  1 import { makeExecutableSchema } from 'graphql-tools';
       2 import resolver from "./resolvers"; //导入resolvers
       3 var requireText = require('require-text');
       4 var Base = requireText('./base.gql', require);
       5 var User = requireText('./user/user.gql', require);
       6 
       7 //基础信息
       8 var typeDefs = [Base];
       9 typeDefs = typeDefs.concat(User);
      10 
      11 const schema = makeExecutableSchema({
      12   typeDefs: typeDefs,
      13   resolvers: resolver  //添加resolvers
      14 })
      15 
      16 
      17 export default schema;
    • 刷新http://localhost:8080/playground 在界面操作应该可以看到如下结果

     最后整个项目结构如下:

    一个最基本的graphql Server 已经可以了,当然下一步就是实现数据真实操作。

  • 相关阅读:
    MySQL 之 创建千万数据测试
    MySQL中的各种引擎
    MySQL 之【约束】【数据库设计】
    MySQL 的增删改查
    SQL数据类型
    SQL 数据类型
    数据库
    摘要算法
    Python 标准库-json
    Python 标准库-sys
  • 原文地址:https://www.cnblogs.com/lslgg/p/8178678.html
Copyright © 2020-2023  润新知