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 已經可以了,當然下一步就是實現數據真實操作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM