UNPKG

mm_os

Version:

这是超级美眉服务端框架,用于快速构建应用程序。

133 lines (124 loc) 3.41 kB
const Item = require('mm_machine').Item; /** * Event事件驱动类 * @extends {Item} * @class */ class Drive extends Item { /** * 构造函数 * @param {String} dir 当前目录 * @constructor */ constructor(dir) { super(dir, __dirname); this.default_file = "./event.json"; // 默认启用热更新 this.mode = 3; /* 通用项 */ // 配置参数 this.config = { // 名称, 由中英文和下“_”组成, 用于修改或卸载 例如: demo "name": "", // 状态 0未启用,1启用 "state": 1, // 标题, 介绍事件作用 "title": "示例事件", // 描述, 用于描述该事件有什么用的 "description": "描述事件使用方法", // 目标 "target": "", // 阶段, 分执行前before、验证check、主要main、渲染render、执行后after阶段 "stage": "main", // 文件路径, 当调用函数不存在时,会先从文件中加载 "func_file": "./main.js", // 回调函数名 用于决定调用脚本的哪个函数 "func_name": "", // 执行顺序, 数字越小,越优先执行 "sort": 100, // 中断循环 "end": true, // 请求方法 "method": "ALL" }; } } /** * 新建脚本 * @param {String} 文件 */ Drive.prototype.new_script = function(file) { var fl = __dirname + "/script.js"; if (fl.hasFile()) { var text = fl.loadText(); if (text) { var l = $.slash; var arr = file.split(l); arr = arr.slice(arr.indexOf('app')); var app_name = arr[1]; var event_name = arr[3]; if (event_name === 'client') { text = text.replaceAll('{0}', app_name + '_' + event_name); } else if (event_name === 'manage') { text = text.replaceAll('{0}', app_name + '_' + event_name); } else { text = text.replaceAll('{0}', event_name); } file.saveText(text); } } }; /** * 新建脚本 * @param {String} 文件 */ Drive.prototype.new_config = function(file) { var fl = __dirname + "/config.tpl.json"; if (fl.hasFile()) { var text = fl.loadText(); if (text) { var l = $.slash; var arr = file.split(l); arr = arr.slice(arr.indexOf('app')); var app_name = arr[1]; var event_name = arr[3]; if (event_name === 'client') { text = text.replaceAll('{0}', app_name + '_' + event_name); text = text.replaceAll('{1}', '/api/' + app_name + '*'); } else if (event_name === 'manage') { text = text.replaceAll('{0}', app_name + '_' + event_name); text = text.replaceAll('{1}', '/apis/' + app_name + '*'); } else { text = text.replaceAll('{0}', event_name); text = text.replaceAll('{1}', '/' + event_name + '*'); } file.saveText(text); } } }; /** * 执行事件 * @param {Object} ctx 请求上下文 * @param {Object} db 数据管理器 * @param {String} method 执行方法 * @return {Object} 执行结果 */ Drive.prototype.run = async function(ctx, db, method = 'main') { var ret; try { ret = await this[method](ctx, db); } catch (error) { $.log.error("事件执行失败!", this.config.name, error); } return ret; }; /** * 脚本主函数 * @param {Object} ctx 请求上下文 * @param {Object} db 数据管理器 * @return {Object} 执行结果 */ Drive.prototype.main = async function(ctx, db) { return null; }; module.exports = Drive;