koahub.js 0.09 公布,新增钩子机制
koahub.js 0.09 发布,新增钩子机制
koahub.js发布0.09 新增钩子机制
添加钩子机制,控制器钩子和函数钩子
修复自动加载bug,实现除自动加载导出的default外,还能自动加载其他的方法
记koahub.js钩子开发过程
在使用koahubjs开发项目完成之后,总是需要另外增加一些插件功能,这种情况下改动项目代码,风险太大,所以钩子机制不可缺少。koahubjs将钩子加载到了内存中,原因是因为koahubjs框架并没有内置数据库,而且加载到内存中更加灵活。
钩子1
控制器钩子
执行某个http请求的时候,想要调用另外一个控制器的方法
钩子2
方法钩子
执行某个http请求的时候,想要调用某个公共的函数
直接上代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
//创建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}`);
}
} |
钩子需要提前挂载到相应的节点上
1
2
3
4
5
6
7
8
9
|
//开始挂载 //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' );
|
util方法
1
2
3
4
5
6
7
8
9
10
11
|
//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;
} |
KoaHub.js – 基于 Koa.js 平台的 Node.js web 快速开发框架
安装
npm install koahubjs --save
Star Github
https://github.com/einsqing/koahubjs
官网:http://js.koahub.com
wemall 开源微商城 ,微信商城,商城源码,三级分销,微生鲜,微水果,微外卖,微订餐---专业的o2o系统
wemall地址:http://www.wemallshop.com