Miao-Yunzai/lib/plugins/handler.js

71 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-10-15 05:35:17 +08:00
import lodash from 'lodash'
let events = {}
let Handler = {
add (cfg) {
let { ns, fn, property = 50 } = cfg
let key = cfg.key || cfg.event
if (!key || !fn) {
return
}
Handler.del(ns, key)
2023-10-15 05:46:34 +08:00
logger.mark(`[Handler][Reg]: [${ns}][${key}]`)
2023-10-15 05:35:17 +08:00
events[key] = events[key] || []
events[key].push({
property,
fn,
ns,
key
})
events[key] = lodash.orderBy(events[key], ['priority'], ['asc'])
},
del (ns, key = '') {
if (!key) {
for (let key in events) {
Handler.del(ns, key)
}
return
}
if (!events[key]) {
return
}
for (let idx = 0; idx < events[key].length; idx++) {
let handler = events[key][idx]
if (handler.ns === ns) {
events[key].splice(idx, 1)
events[key] = lodash.orderBy(events[key], ['priority'], ['asc'])
}
}
},
async callAll (key, e, args) {
return await Handler.callAll(key, e, args, true)
},
async call (key, e, args, allHandler = false) {
let ret
for (let obj of events[key]) {
let fn = obj.fn
let done = true
let reject = (msg = '') => {
if (msg) {
2023-10-15 05:46:34 +08:00
logger.mark(`[Handler][Reject]: [${obj.ns}][${key}] ${msg}`)
2023-10-15 05:35:17 +08:00
}
done = false
}
ret = fn(e, args, reject)
if (ret) {
await ret
}
if (done && !allHandler) {
2023-10-15 05:46:34 +08:00
logger.mark(`[Handler][Done]: [${obj.ns}][${key}]`)
2023-10-15 05:35:17 +08:00
return ret
}
}
return ret
},
has (key) {
return !!events[key]
}
}
export default Handler