elpis-core
基于koa实现后端开发应用架构
- 为什么要构造elpis-core loader?
- 方便开发者只关注业务逻辑,而不用去考虑:
- 中间件的植入 middwareLoader
- 业务参数校验-jsonSchema routerSchemaloader
- 业务主要逻辑处理 controllerLoader
- 数据采集 serviceLoader
- 配置文件的设置 configLoader
- 挂载插件 extendLoader
- 挂载路由 routerLoader
- 约定目录结构
- Elpis | - app | - routerSchema | | - demo.js | - router | - controller | - service | - middleware | - config | - extend - 原理:
- 当项目启动时,创建Koa实例;
- 根据elpis-core 去读取上述文件目录;
- 按照特定的方法依次构造;
- 然后挂在到Koa实例上,启动服务。
- config
根据项目不同的环境,加载不同的配置文件
// 获取默认配置
try {
defaultConfig = require('../')
} catch (error) {
console.log(`[exception] there is no default.config file`);
}
let envConfig = {}
try {
// 获取env.config
if (app.env.isLocal()) {
envConfig = require(path.resolve(busConfigPath, `.${sep}config.local.js`));
} else if (app.env.isBeta()) {
envConfig = require(path.resolve(busConfigPath, `.${sep}config.beta.js`));
} else if (app.env.isProd()) {
envConfig = require(path.resolve(busConfigPath, `.${sep}config.prod.js`));
}
} catch (error) {
console.log(`[exception] there is no env.config file`);
}
// 覆盖config配置
app.config = Object.assign(defaultConfig, envConfig);
- controller
读取文件的目录,然后挂载在app上
* 例子
* app/controller
* |
* |-- user
* |
* |-- login.js
*
* => app.controller.user.login
fileList.forEach(file => {
let name = path.resolve(file)
// 截取路径
name = name.substring(name.lastIndexOf(`controller${sep}`) + `controller${sep}`.length, name.lastIndexOf('.'));
// 把'-_',改成驼峰命名
name = name.replace(/[_-][a-z]/ig, (s) => s.substring(1).toUpperCase())
// 挂在到 middleweare 到app对象中
let tmp = controller
let names = name.split(sep)
for (let i = 0; i < names.length; i++) {
if (i == names.length - 1) {
// 目录的最后文件
const ControllerModule = require(path.resolve(file))(app);
tmp[names[i]] = new ControllerModule();
} else {
// 文件夹
if (!tmp[names[i]]) {
tmp[names[i]] = {}
tmp = tmp[names[i]]
}
}
}
})
app.controller = controller
- 其他loader类似这个原理。
总结:
elpis-core:这个内核其实就是封装好了一个基于Koa的后端服务框架,开发者根据目录结构,能够快速开发出api接口。

评论 0
还没有评论,来坐沙发