当前位置: 首页 > 后端技术 > Node.js

造轮子系列---注解、插件node.jsweb-restfulapi框架

时间:2023-04-03 12:20:43 Node.js

polix是一个基于koav2.5.0的IOC和插件开发框架。与通常的Node.jsWebFramework相比,不需要额外的Binding路由集合,可扩展,易于开发,根据java著名的依赖注入框架spring制作,让开发者专注于逻辑。Polix采用多服务多进程架构,保证服务稳定和快速响应。polix的中间件兼容koav2.x的中间件。默认使用的ORM是sequelize(后面会提供polix-orm)。开发者可以选择ES6/7/8或者TypeScript进行开发。$npmipolix--saveGettingStarted使用polix-cli开始化应用$npmipolix-cli-g$polinitexample&&cdexample$makebuild&&makedevService在service文件夹下添加user.jsconst{Service}=require('polix');classUserServiceextendsService{constructor(){super();这个._name={};}asyncaddUser(userId,name){this._name[userId]=name;归还这个;}asyncgetUser(userId){returnthis._name[userId];}}module.exports=UserService;Controller在controller文件夹下添加user.jsconst{Controller,GET,POST,DEL,PUT}=require('polix');classUserControllerextendsController{//POST/user/addUser@POSTasyncaddUser(param,ctx){awaitthis.service.user.addUser(param.userId,param.name);ctx.body={结果:'ok'};}//GET/user/getUser@GETasyncgetUser(param,ctx){letuser=awaitthis.service.user.getUser(param.userId);ctx.body={用户};}//GET/user/info@GET('info')asyncgetInfo(param,ctx){ctx.body={v:'v1.0'}}//PUT/user/updateUser@PUTasyncupdateUser(param,ctx){ctx.body={status:true}}//DEL/user/delUser@DELasyncdelUser(param,ctx){ctx.body={status:true};}//GET/user/status/:userId@GET('status/:userId')asyncgetStatus(param,ctx){ctx.body={status:true,userId:param.userId};}}module.exports=UserController;Middwarepolix中间件兼容koa2.x中间件。框架默认加载koa-body中间件。如果需要添加额外的中间件,新建middware文件夹(与controller文件夹同级)添加跨域中间件,新建cors.js:exports=function(){returncors({origin:function(ctx){return'*';},exposeHeaders:['WWW-Authenticate','Server-Authorization'],maxAge:5,credentials:true,allowMethods:['GET','POST','DELETE'],allowHeaders:['Content-Type','Authorization','Accept']});}该文件夹下必须有一个index.js文件作为总的输出中间件文件,加载时按照输出对象的顺序绑定中间件#index.jsconstcors=require('./cors');module.exports={cors//必须是一个函数,绑定方式为:app.use(cors())}Plugin$npmi--savepolix-requestin在plugin.default.js下添加如下代码项目根目录下的config文件夹//`curl`最终会挂载到`this.app`下exports.curl={//表示是否启用插件enable:true,//插件`npm`包名package:'polix-请求'};在控制器中使用polix-request@GETasyncgetWebInfo(param,ctx){letresult=awaitthis.app.curl.get('https://www.baidu.com');ctx.body={data:result}}polix内置了polix-request插件,这里只是一个demoStart$makedev地址:polix.js