1. 程式人生 > >Swagger+NodeJS Mock前端資料

Swagger+NodeJS Mock前端資料

現在Web開發越來越傾向於前後端分離,前端使用AngularJS,React,Vue等,部署在NodeJS上,後面採用SpringBoot釋出Rest服務,前後端進行分離。這樣的架構靈活且特別適合大型團隊的協作開發。 那麼問題來了,因為前端都是和後端通過API進行互動的,那麼如果後端沒有開發完成,前端的進度超前了,難道前端要等後端開發完了才能繼續當前或者下一個功能的開發嗎? 有沒有一種方式可以不必等後端的API實現開發完,前端也能把相應的功能渲染出來呢?其實方案有很多種,比如用deployd, swagger+Node等方式,或者通過Swagger+EasyMock。
其實筆者認為deloyd也挺好用的,大家可以

參考這篇文章

但是由於在Swagger提供的功能更為強大,不但可以與SpringBoot整合,還可以與NodeJS整合,還能通過網頁進行線上編輯API的介面定義,更為牛的是還能生成的介面網頁上直接進行測試。既然功能這麼強大,我想其應該有和deployd類似的功能,結果還真被我發現了,只不過配置起來比deployd稍微複雜一些。

1. 首先安裝swagger

加上讀者已經安裝了最新版的nodejs,然後在cmd上輸入下面的命令

npm install -g swagger

2. 建立一個swagger的專案

swagger project create movie-collection

建立好後項目結構如下:

-- api  
---- controllers 
------ hello_world.js
---- helpers
---- mocks
---- swagger
------ swagger.yaml

-- config 
---- default.yaml

-- test
---- api
------ controllers
-------- hello_world.js
------ helpers

-- app.js
-- package.json

3. 啟動當前的swagger的編輯頁面

swagger project edit

將會開啟當前的swagger的編輯介面,然後在左邊的編輯頁面輸入下面的swagger的yaml描述

swagger: "2.0"
info:
  version: "0.0.1"
  title: Hello World App
# during dev, should point to your local machine
host: localhost:10010
# basePath prefixes all resource paths
basePath: /
#
schemes:
  # tip: remove http to make production-grade
  - http
  - https
# format of bodies a client can send (Content-Type)
consumes:
  - application/json
# format of the responses to the client (Accepts)
produces:
  - application/json
paths:
  /movie:
    # our controller name
    x-swagger-router-controller: movie
    get:
      #in /movie
      operationId: getAll
      description: get the movies list
      # define the type of response for Success "200" and Error
      responses:
        "200":
          description: Success
          schema:
            $ref: "#/definitions/GetMoviesListResponse"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
    post:
      operationId: save
      description: add a new movie to the list
      # movie info to be stored
      parameters:
        - name: title
          description: Movie properties
          in: body
          required: true
          schema:
            $ref: "#/definitions/Movie"
      responses:
        "200":
          description: Success
          schema:
            $ref: "#/definitions/GeneralResponse"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
  /movie/{id}:
    # our controller name
    x-swagger-router-controller: movie
    get:
      operationId: getOne
      description: get a movie
      # define the type of response for Success "200" and Error
      parameters:
        - name: id
          type: string
          in: path
          required: true
      responses:
        "200":
          description: Success
          schema:
            $ref: "#/definitions/GetMovieResponse"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
    put:
      operationId: update
      description: update a movie
      # define the parameters
      parameters:
        - name: id
          description: Movie id
          type: string
          in: path
          required: true
        - name: title
          description: Movie properties
          in: body
          required: true
          schema:
            $ref: "#/definitions/Movie"
      responses:
        "200":
          description: Success
          schema:
            $ref: "#/definitions/GeneralResponse"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
    delete:
      operationId: delMovie
      description: delete a movie
      # define the parameters
      parameters:
        - name: id
          description: Movie id
          type: string
          in: path
          required: true
      responses:
        "200":
          description: Success
          schema:
            $ref: "#/definitions/GeneralResponse"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
  /swagger:
    x-swagger-pipe: swagger_raw
# complex objects have schema definitions
definitions:
  GetMoviesListResponse:
    required:
      - movies
    properties:
      # The array of movies
      movies:
        type: array
        items:
          type: object
          properties:
            id:
              type: string
            title:
              type: string
            year:
              type: number
  ErrorResponse:
    required:
      - message
    properties:
      message:
        type: string
  Movie:
    type: object
    properties:
      title:
        type: string
        description: task object name
      year:
        type: number
        description: task description
    required:
      - title
      - year
  GeneralResponse:
    type: object
    properties:
      success:
        type: number
        description: returns 1 if successful
      description:
        type: string
        description: a short comment
    required:
      - success
      - description
  GetMovieResponse:
    required:
      - id
      - title
      - year
    properties:
      id:
        type: string
      title:
        type: string
      year:
        type: number

其定義了下面的一些API REST介面,

這裡寫圖片描述

4. 編輯 在api–>Controllers目錄下新建一個movie.js檔案

上面的API已經暴露出來了,但是直接呼叫的話,是呼叫不成功的。因為我們剛剛生成的swagger專案沒有啟動,movie-collection,為了返回我們想要的資料,
我們可以修改api–>Controllers–>movie.js檔案,在修改檔案之前,我們先安裝一個nodejs的記憶體資料庫包:crypto ,安裝命令如下:

npm install crypto --save

安裝好後,修改hello_world.js檔案,把下面的程式碼黏貼上。

'use strict';
    // Include our "db"
    var db = require('../../config/db')();
    // Exports all the functions to perform on the db
    module.exports = {getAll, save, getOne, update, delMovie};

    //GET /movie operationId
    function getAll(req, res, next) {
      res.json({ movies: db.find()});
    }
    //POST /movie operationId
    function save(req, res, next) {
        res.json({success: db.save(req.body), description: "Movie added to the list!"});
    }
    //GET /movie/{id} operationId
    function getOne(req, res, next) {
        var id = req.swagger.params.id.value; //req.swagger contains the path parameters
        var movie = db.find(id);
        if(movie) {
            res.json(movie);
        }else {
            res.status(204).send();
        }
    }
    //PUT /movie/{id} operationId
    function update(req, res, next) {
        var id = req.swagger.params.id.value; //req.swagger contains the path parameters
        var movie = req.body;
        if(db.update(id, movie)){
            res.json({success: 1, description: "Movie updated!"});
        }else{
            res.status(204).send();
        }

    }
    //DELETE /movie/{id} operationId
    function delMovie(req, res, next) {
        var id = req.swagger.params.id.value; //req.swagger contains the path parameters
        if(db.remove(id)){
            res.json({success: 1, description: "Movie deleted!"});
        }else{
            res.status(204).send();
        }

    }

5. 啟動movie-collection的swagger專案

通過下面的命令啟動swagger的movie-collection專案

swagger project start

注意不能通過下面的命令啟動,否則其只會啟動debug模式

swagger project start -m

6. 直接swager edit頁面進行測試

比如我們新建立一個movie的記錄,從下面可以看出其建立成功了。

這裡寫圖片描述

在建立一條,
這裡寫圖片描述

然後,在得到所有的記錄,可知前面兩條記錄建立成功。
這裡寫圖片描述