MWSE/frontend/EventPool.ts

68 lines
2.0 KiB
TypeScript

import MWSE from "./index";
import { Message } from "./WSTSProtocol";
export default class EventPool
{
public wsts : MWSE;
public events : Map<number, [Function,Function]> = new Map();
public signals : Map<string, Function[]> = new Map();
public requests : Map<number, [Function,Function]> = new Map();
public count = 0;
constructor(wsts:MWSE){
this.wsts = wsts;
}
/**
* request sends a packet that expects a correlated reply and resolves with it.
* Use it ONLY for response-bearing packets. For fire-and-forget (WOM) packets
* use only(): registering a waiter for a packet the server never answers leaves
* a promise pending forever (issue #33).
*/
public request(msg: Message) : Promise<any>
{
return new Promise((ok,rej) => {
let id = ++this.count;
this.events.set(id,[
(data:any) => {
ok(data);
},
(data:any) => {
rej(data);
}
]);
this.wsts.WSTSProtocol.SendRequest(msg, id);
})
}
/**
* only is the WOM (without-me / fire-and-forget) path: it sends the packet and
* leaves NO pending waiter. The engine deliberately does not reply to these
* relays (it returns nil), so there is nothing to await. This is the separation
* issue #33 requires: request() = response-bearing, only() = WOM.
*/
public only(msg: Message)
{
this.wsts.WSTSProtocol.SendOnly(msg);
}
public stream(msg: Message, callback: Function)
{
let id = ++this.count;
this.wsts.WSTSProtocol.StartStream(msg, id);
this.events.set(id,[
(data:any) => {
callback(data);
},
() => { }
]);
}
public signal(event: string, callback: Function)
{
let T = this.signals.get(event);
if(!T)
{
this.signals.set(event, [callback]);
}else{
T.push(callback);
}
}
}