silverbullet/plug-api/syscalls/event.ts

48 lines
1.3 KiB
TypeScript
Raw Normal View History

import { syscall } from "../syscall.ts";
2022-04-01 23:07:08 +08:00
2024-08-09 15:27:58 +08:00
/**
* Exposes the SilverBullet event bus.
* @module
*/
2024-08-07 19:27:25 +08:00
/**
* Triggers an event on the SilverBullet event bus.
* This can be used to implement an RPC-style system too, because event handlers can return values,
* which are then accumulated in an array and returned to the caller.
* @param eventName the name of the event to trigger
* @param data payload to send with the event
* @param timeout optional timeout in milliseconds to wait for a response
* @returns an array of responses from the event handlers (if any)
*/
2022-10-14 21:11:33 +08:00
export function dispatchEvent(
eventName: string,
data: any,
timeout?: number,
): Promise<any[]> {
return new Promise((resolve, reject) => {
let timeouter: any = -1;
if (timeout) {
timeouter = setTimeout(() => {
console.log("Timeout!");
reject("timeout");
}, timeout);
}
syscall("event.dispatch", eventName, data)
2024-07-30 23:24:17 +08:00
.then((r: any) => {
if (timeouter !== -1) {
clearTimeout(timeouter);
}
resolve(r);
})
.catch(reject);
});
2022-04-01 23:07:08 +08:00
}
2024-08-07 19:27:25 +08:00
/**
* List all events currently registered (listened to) on the SilverBullet event bus.
* @returns an array of event names
*/
export function listEvents(): Promise<string[]> {
return syscall("event.list");
}