2023-10-16 04:11:44 +08:00
|
|
|
import util from 'node:util'
|
2023-10-15 05:35:17 +08:00
|
|
|
import lodash from 'lodash'
|
|
|
|
|
|
|
|
let events = {}
|
|
|
|
let Handler = {
|
|
|
|
add (cfg) {
|
2023-10-16 04:11:44 +08:00
|
|
|
let { ns, fn, self, property = 50 } = cfg
|
2023-10-15 05:35:17 +08:00
|
|
|
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,
|
2023-10-16 04:11:44 +08:00
|
|
|
self,
|
2023-10-15 05:35:17 +08:00
|
|
|
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) {
|
2023-10-16 04:11:44 +08:00
|
|
|
// 暂时屏蔽调用
|
|
|
|
// return Handler.call(key, e, args, true)
|
2023-10-15 05:35:17 +08:00
|
|
|
},
|
|
|
|
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
|
|
|
|
}
|
2023-10-16 04:11:44 +08:00
|
|
|
ret = fn.call(obj.self, e, args, reject)
|
|
|
|
if (util.types.isPromise(ret)) {
|
|
|
|
ret = await ret
|
2023-10-15 05:35:17 +08:00
|
|
|
}
|
|
|
|
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
|
|
|
|
|