yapi/client/plugin.js

86 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-10-05 09:12:44 +08:00
let hooks, pluginModule;
2017-09-05 10:24:13 +08:00
2017-09-05 17:04:59 +08:00
/**
2017-09-15 12:01:17 +08:00
* type component 组件
* listener 监听函数
* mulit 是否绑定多个监听函数
2017-09-05 17:04:59 +08:00
*
*/
2017-09-15 12:01:17 +08:00
hooks = {
2017-09-17 13:36:51 +08:00
third_login: {
2017-09-15 12:01:17 +08:00
type: 'component',
mulit: false,
2017-09-05 17:04:59 +08:00
listener: null
2017-09-05 10:24:13 +08:00
},
2017-09-17 13:36:51 +08:00
add_interface: {
2017-09-15 12:01:17 +08:00
type: 'listener',
mulit: true,
listener: []
},
import_data: {
type: 'listener',
mulit: true,
2017-09-05 17:04:59 +08:00
listener: []
2017-09-17 13:36:51 +08:00
},
interface_tab: {
type: 'listener',
mulit: true,
listener: []
2017-09-05 10:24:13 +08:00
}
};
2017-09-05 17:04:59 +08:00
function bindHook(name, listener) {
2017-09-05 10:24:13 +08:00
if (!name) throw new Error('缺少hookname');
if (name in hooks === false) {
throw new Error('不存在的hookname');
}
2017-09-15 12:01:17 +08:00
if (hooks[name].mulit === true) {
2017-09-05 17:04:59 +08:00
hooks[name].listener.push(listener);
2017-09-05 10:24:13 +08:00
} else {
2017-09-05 17:04:59 +08:00
hooks[name].listener = listener;
2017-09-05 10:24:13 +08:00
}
}
2017-09-17 13:36:51 +08:00
function emitHook(name, ...args) {
if (!hooks[name]) throw new Error('不存在的hook name');
2017-09-15 12:01:17 +08:00
let hook = hooks[name];
2017-09-17 13:36:51 +08:00
if (hook.mulit === true && hook.type === 'listener') {
if (Array.isArray(hook.listener)) {
hook.listener.forEach(item => {
if (typeof item === 'function') {
2017-09-15 12:01:17 +08:00
item.call(pluginModule, ...args)
}
})
}
2017-09-17 13:36:51 +08:00
} else if (hook.mulit === false && hook.type === 'listener') {
if (typeof hook.listener === 'function') {
2017-09-15 12:01:17 +08:00
hook.listener.call(pluginModule, ...args);
}
2017-09-17 13:36:51 +08:00
} else if (hook.type === 'component') {
2017-09-15 12:01:17 +08:00
return hook.listener;
}
2017-09-05 17:04:59 +08:00
2017-09-17 13:36:51 +08:00
}
2017-09-15 12:01:17 +08:00
2017-09-17 13:36:51 +08:00
pluginModule = {
hooks: hooks,
bindHook: bindHook,
emitHook: emitHook
2017-09-05 10:24:13 +08:00
}
2017-09-28 20:40:29 +08:00
let pluginModuleList;
try{
pluginModuleList = require('./plugin-module.js');
}catch(err){pluginModuleList = {}}
2017-09-05 10:24:13 +08:00
2017-10-05 09:12:44 +08:00
Object.keys(pluginModuleList).forEach(plugin=>{
if (!pluginModuleList[plugin]) return null;
if(pluginModuleList[plugin] && typeof pluginModuleList[plugin].module === 'function'){
pluginModuleList[plugin].module.call(pluginModule, pluginModuleList[plugin].options)
2017-09-17 13:36:51 +08:00
}
2017-09-15 12:01:17 +08:00
})
module.exports = pluginModule;