在
npmjs
上搜索关于koa
路由装饰器的已经有那么几个包了,可是我从几个包中发现做者的思惟仅仅限制于前端开发的思想,项目分层不明确,咱们开发kow-web
项目能够根据java-web
中项目分层的思想来写项目,项目结构清晰明了,本人封装这个包也是参考了java-web
开发过程当中把项目分为四层架构。前端
controllers
:路由的控制servers
:经常使用于一些业务逻辑的判断dao
:操做数据库的models
:关于建表的数据模型koa2-router-decors
包的使用步骤一、构建一个项目,并建立分层目录java
二、安装mysql
npm install koa2-router-decors
// or
yarn add koa2-router-decors
复制代码
三、在中间件中使用咱们安装的包git
import { resolve } from 'path';
import Route from 'koa2-router-decors';
// 能够写到config中统一配置
const API_VERSION = '/api/v1';
/** * @Description: 反转路径的方法 * @param {String} * @return: */
const dir = path => resolve(__dirname, path);
/** * @Description: 路由中间件读取controllers中的装饰器配置 * @param {type} * @return: */
export default (app) => {
// 这个地方是要读取的文件夹目录
const apiPath = dir('../controllers/*');
// 实例化类并调用方法
const route = new Route(app, apiPath, API_VERSION);
route.init();
};
复制代码
四、使用中间件github
五、在controllers
的文件夹中使用装饰器web
@controller('/user')
export class UserController extends BaseController {
constructor() {
super();
}
/** * * @api {post} /api/v1/user/create/ 添加用户 * @apiDescription 建立用户的接口 * @apiName createUser * @apiGroup users * @apiVersion 0.1.0 * @apiParam {string} username="张三" 用户名 * @apiParam {string} mobile 手机号码 * @apiParam {string} email 邮箱 * @apiParam {string} password 密码 */
@post('/create')
@required({ body: ['username', 'mobile', 'password'] })
async createUser(ctx) {
const result = await UserServer.createUser(ctx.request.body);
ctx.success(result);
}
....
}
复制代码
六、具体代码能够参考example
中写的sql
example
代码跑起来的说明一、使用的是mysql
数据库
二、mysql
建表sql
npm
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`mobile` varchar(11) DEFAULT NULL,
`email` varchar(20) DEFAULT NULL,
`password` varchar(255) NOT NULL,
`created_at` datetime DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8
复制代码
三、在example
的根目录下建立一个.env
的文件api
DB_HOST=数据库地址
DB_USERNAME=数据库链接名
DB_PASSWORD=数据库链接密码
DB_DATABASE=数据库名
复制代码