ms/packages/api/src/channel.ts

67 lines
2.2 KiB
TypeScript
Raw Normal View History

import { injectable } from "@ccms/container"
export namespace channel {
/**
* handle plugin message
* @param data byte[]
*/
export type ChannelListener = (data: any, exts?: any) => void
@injectable()
export abstract class Channel {
private listenerMap = [];
/**
*
* @param plugin
* @param channel
* @param exec
*/
listen(plugin: any, channel: string, exec: ChannelListener) {
2020-09-17 09:44:48 +00:00
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!')
let name = plugin.description.name
let listener = this.register(channel, exec)
2020-09-17 09:44:48 +00:00
if (!this.listenerMap[name]) this.listenerMap[name] = []
let offExec = () => {
2020-09-17 09:44:48 +00:00
this.unregister(channel, listener)
console.debug(`[${name}] unregister channel ${channel}`)
}
var off = {
channel,
listener,
off: offExec
2020-09-17 09:44:48 +00:00
}
this.listenerMap[name].push(off)
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`)
return off
}
/**
*
* @param plugin
*/
disable(plugin: any) {
2020-09-17 09:44:48 +00:00
var channelCache = this.listenerMap[plugin.description.name]
if (channelCache) {
2020-09-17 09:44:48 +00:00
channelCache.forEach(t => t.off())
delete this.listenerMap[plugin.description.name]
}
}
/**
* Send Channel Message
* @param player recover target
* @param channel ChannelName
* @param data byte[]
*/
abstract send(player: any, channel: string, data: any)
/**
* register channel
* @param channel ChannelName
*/
abstract register(channel: string, listener: ChannelListener): any
/**
* unregister channel
* @param channel ChannelName
*/
abstract unregister(channel: string, listener?: any): void
}
}