mm_os
Version:
这是超级美眉服务端框架,用于快速构建应用程序。
153 lines (141 loc) • 3.21 kB
JavaScript
class Middleware {
/**
* 构造函数
* @param {Object} config 配置参数
*/
constructor(config) {
// 中间件列表
this.list = [];
this.config = {
path: "./middleware".fullname($.runPath),
file: "middleware.json",
mode: "web"
};
this.init(config);
}
}
Middleware.prototype.init = function(config) {
if (config) {
Object.assign(this.config, config);
}
}
/**
* 新建脚本
* @param {String} 文件
*/
Middleware.prototype.new_script = function(file) {
var fl = __dirname + "/script.js";
if (fl.hasFile()) {
var text = fl.loadText();
if (text) {
var l = $.slash;
if (file.indexOf('middleware' + l) !== -1) {
var name = file.between('middleware' + l, l);
text = text.replaceAll("{0}", name);
}
file.saveText(text);
}
}
};
/**
* 新建配置
* @param {String} 文件
*/
Middleware.prototype.new_config = function(file) {
var fl = __dirname + "/config.tpl.json";
if (fl.hasFile()) {
var text = fl.loadText();
if (text) {
var l = $.slash;
if (file.indexOf('middleware' + l) !== -1) {
var name = file.between('middleware' + l, l);
text = text.replaceAll("{0}", name);
}
file.saveText(text);
}
}
};
/**
* 加载配置
* @param {String} file 配置文件路径
*/
Middleware.prototype.load_item = function(file) {
var config = file.loadJson();
if (config) {
var cg = this.list.getObj({
name: config.name
});
if (cg) {
$.push(cg, config, true);
} else {
cg = {
func_file: file.replace(this.config.file, 'index.js')
}
$.push(cg, config, true);
this.list.push(cg);
}
} else {
this.new_config(file);
}
var script_file = file.replace('middleware.json', 'index.js');
if (!script_file.hasFile()) {
this.new_script(script_file);
}
};
/**
* 遍历加载配置
* @param {Object} path
*/
Middleware.prototype.update_config_all = function(path, accurate) {
if (path.hasDir()) {
var dirs = $.dir.getAll(path);
// 遍历目录路径
var file = this.config.file;
for (var i = 0; i < dirs.length; i++) {
var d = dirs[i];
this.load_item(d + file);
}
}
};
/**
* 排序
*/
Middleware.prototype.sort = function() {
return this.list.sortBy('asc', 'sort');
};
/**
* 清除接口缓存
*/
Middleware.prototype.clear = function() {
this.list = [];
};
/**
* 遍历加载配置
*/
Middleware.prototype.update_config = function(path, accurate = true, clear = true) {
if (clear) {
this.clear();
}
this.update_config_all("../../../middleware/".fullname(__dirname));
if (path) {
this.update_config_all(path);
}
this.update_config_all(this.config.path);
var p = "./middleware".fullname($.runPath);
if (this.config.path !== p) {
this.update_config_all(p);
}
this.sort();
};
/**
* 更新
* @param {String} dir 检索的路径
* @param {Boolean} loadJS 是否加载JS
*/
Middleware.prototype.update = function(dir, accurate = true, loadJS = true, clear = true) {
this.update_config(dir, accurate, clear);
}
if (!$.middleware) {
$.middleware = new Middleware();
}
module.exports = Middleware;