先放地址:https://github.com/polixjs/polix
polix
是基于koa v2.5.0
的IOC
腹备、插件式開發(fā)框架,和平常的Node.js Web Framework
相比感憾,它無需另外綁定路由集合谭贪、可拓展境钟、開發(fā)簡(jiǎn)單,依照java
的著名依賴注入框架spring
來制作俭识,讓開發(fā)者專注于邏輯慨削。polix
采用多服務(wù)多進(jìn)程架構(gòu)來保證服務(wù)的穩(wěn)定和快速響應(yīng)能力。polix
的中間件和koa v2.x
的中間件保持兼容套媚。默認(rèn)使用的ORM
是sequelize
(后續(xù)會(huì)提供polix-orm
)缚态。開發(fā)者可以選擇ES6/7/8 或者 TypeScript來進(jìn)行開發(fā)。
$ npm i polix --save
Getting Started
使用
polix-cli
初始化應(yīng)用
$ 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 的中間件保持兼容
框架默認(rèn)加載koa-body
中間件凑阶,如需另外添加中間件則新建middware
文件夾(與controller
文件夾平級(jí))
添加跨域中間件 猿规,新建cors.js
:
# 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
文件作為總輸出中間件文件,加載時(shí)根據(jù)導(dǎo)出對(duì)象的順序進(jìn)行綁定中間件
# index.js
const cors = require('./cors');
module.exports = {
cors // 必須是函數(shù) ,綁定方式為:app.use(cors())
}
Plugin
$ npm i --save polix-request
在項(xiàng)目根目錄下的
config
文件夾下的plugin.default.js
中添加以下代碼
// `curl`最終會(huì)掛載到`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
已經(jīng)內(nèi)置polix-request
插件了,這里只是個(gè)演示
Start
$ make dev
覺得好的可以給個(gè)star~