红联Linux门户
Linux帮助

koahubjs 0.09发布,新增钩子机制

发布时间:2016-10-08 22:31:58来源:红联作者:lovsher
koahubjs发布0.09 新增钩子机制

添加钩子机制,控制器钩子和函数钩子
修复自动加载bug,实现除自动加载导出的default外,还能自动加载其他的方法
记koahubjs钩子开发过程

在使用koahubjs开发项目完成之后,总是需要另外增加一些插件功能,这种情况下改动项目代码,风险太大,所以钩子机制不可缺少。koahubjs将钩子加载到了内存中,原因是因为koahubjs框架并没有内置数据库,而且加载到内存中更加灵活。
钩子1
控制器钩子

执行某个http请求的时候,想要调用另外一个控制器的方法
钩子2
方法钩子

执行某个http请求的时候,想要调用某个公共的函数

直接上代码[code]//创建hook.class.js
// hooks 定义
// {
// addOrder: [
// '/admin/index/index'
// ]
// }

export default class {
constructor() {
this.hooks = {};
}

get() {
return this.hooks;
}

add(name, action) {
let add = true;
for (let key in this.hooks) {
if (name == key) {
this.hooks[key].push(action);
add = false;
}
}
if (add) {
this.hooks[name] = [action];
}

return this.get();
}

run(name) {
for (let key in this.hooks) {
if (name == key) {
for (let path of this.hooks[key]) {
if (/\w+\(.*\)$/.test(path)) {
this.runFunction(path);
} else {
this.runController(path);
}
}
}
}
}

runController(path) {
let action = path.slice(path.lastIndexOf('/'));
path = path.slice(0, path.lastIndexOf('/'));

let include = false;
for (let _key in koahub.controllers) {
if (_key == path) {
include = true;
break;
}
}

if (include) {
let ctrl = koahub.controllers[path];
let pros = Object.getOwnPropertyNames(ctrl.prototype).filter(function(value) {
if (value == 'constructor') {
return false;
}
return true;
});

let callFlag = true;
for (let k in pros) {
if ('/' + pros[k] == action) {
Object.getPrototypeOf(new ctrl())[pros[k]].call(this);
callFlag = false;
}
}

if (callFlag) {
console.error('Hook Not Found Method');
}
} else {
console.error('Hook Not Found Controller');
}
}

runFunction(value) {
eval(`koahub.utils.${value}`);
}
}[/code]钩子需要提前挂载到相应的节点上[code]//开始挂载
//controller钩子
koahub.hook.add('hook1', '/admin/public/sendEmail');
//function钩子
koahub.hook.add('hook2', 'tools.add(1,2)');

//调用钩子
koahub.hook.run('hook1');
koahub.hook.run('hook2');[/code]util方法[code]//util下的*.util.js会自动挂载到koahub.utils上
//util/tools.util.js
export function add(a, b) {
console.log(a + b);
return a + b;
}

export function dis(a, b) {
console.log(a - b);
return a - b;
}[/code]KoaHub.js - 基于 Koa.js 平台的 Node.js web 快速开发框架

安装

npm install koahubjs --save

软件详情:http://js.koahub.com/

下载地址:https://github.com/einsqing/koahubjs

来自:开源中国社区
文章评论

共有 0 条评论