造輪子系列 --- 註解、插件式node.js web / restful api 框架

polix是基於koa v2.5.0IOC、插件式開發框架,和日常的Node.js Web Framework相比,它無需另外綁定路由集合、可拓展、開發簡單,依照java的著名依賴注入框架spring來製做,讓開發者專一於邏輯。polix採用多服務多進程架構來保證服務的穩定和快速響應能力。polix的中間件和koa v2.x的中間件保持兼容。默認使用的ORMsequelize(後續會提供polix-orm)。開發者能夠選擇ES6/7/8 或者 TypeScript來進行開發。javascript

$ npm i polix --save

Getting Started

使用 polix-cli初始化應用
$ npm i polix-cli -g
$ pol init example && cd example
$ make build && make dev

Service

service文件夾下添加 user.js
const { Service } = require('polix');

class UserService extends Service {
  constructor(){
    super();
    this._name = {};
  }

  async addUser(userId,name){
    this._name[userId] = name;
    return this;
  }

  async getUser(userId){
    return this._name[userId];
  }
}

module.exports = UserService;

Controller

controller文件夾下添加 user.js
const { Controller, GET, POST, DEL, PUT  } = require('polix');

class UserController extends Controller {
  
  // POST /user/addUser
  @POST
  async addUser(param, ctx){
    await this.service.user.addUser(param.userId,param.name);
    ctx.body = {
      result: 'ok'
    };
  }

  // GET /user/getUser
  @GET
  async getUser(param, ctx){
    let user = await this.service.user.getUser(param.userId);
    ctx.body = {
      user
    };
  }

  // GET /user/info
  @GET('info')
  async getInfo(param, ctx){
    ctx.body = {
      v: 'v1.0'
    }
  }

  // PUT /user/updateUser
  @PUT
  async updateUser(param, ctx){
    ctx.body = {
      status: true
    }
  }

  // DEL /user/delUser
  @DEL
  async delUser(param, ctx){
    ctx.body = {
      status: true
    };
  }

  // GET /user/status/:userId
  @GET('status/:userId')
  async getStatus(param, ctx){
    ctx.body = {
      status: true,
      userId: param.userId
    };
  }

}

module.exports = UserController;

Middware

polix的中間件與koa 2.x 的中間件保持兼容
框架默認加載koa-body中間件,如需另外添加中間件則新建middware文件夾(與controller文件夾平級)
添加跨域中間件 ,新建cors.js:java

# cors.js

const cors = require('koa2-cors');
module.exports = function(){
  return cors({
    origin: function(ctx) {
      return '*';
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept']
  });
}

該文件夾下必須存在index.js文件做爲總輸出中間件文件,加載時根據導出對象的順序進行綁定中間件git

# index.js

const cors = require('./cors');

module.exports = {
    cors // 必須是函數 ,綁定方式爲:app.use(cors())
}

Plugin

$ npm i --save polix-request
在項目根目錄下的 config文件夾下的 plugin.default.js中添加如下代碼
// `curl`最終會掛載到`this.app`下
exports.curl = {
  // 表示是否啓用該插件
  enable: true,
  // 插件`npm`包名
  package: 'polix-request'
};
controller裏用 polix-request
@GET
  async getWebInfo(param, ctx){
    let result = await this.app.curl.get('https://www.baidu.com');
    ctx.body = {
      data: result
    }
  }
polix已經內置 polix-request插件了,這裏只是個演示

Start

$ make dev

地址:polix.jsgithub

相關文章
相關標籤/搜索