UNPKG

rjweb-server

Version:

Easy and Robust Way to create a Web Server with Many Easy-to-use Features in NodeJS

77 lines (76 loc) 2.18 kB
import parseContent from "../functions/parseContent"; import { array, as, number } from "@rjweb/utils"; export default class Channel { /** * Create a new Channel * @example * ``` * import { Server, Channel } from "rjweb-server" * import { Runtime } from "@rjweb/runtime-bun" * * const echo = new Channel<string>() * * const server = new Server(Runtime, { * port: 8000 * }) * * server.path('/', (path) => path * .ws('/echo', (ws) => ws * .onOpen((ctr) => { * ctr.printChannel(echo) * }) * .onMessage((ctr) => { * echo.send(ctr.rawMessage()) // will send the message to all subscribed sockets * }) * ) * .http('GET', '/last-echo', (http) => http * .onRequest((ctr) => { * return ctr.print(echo.last()) * }) * ) * ) * * server.start().then(() => console.log('Server Started!')) * ``` * @since 9.0.0 */ constructor(id, initial) { this.listeners = []; this.onPublish = null; this.data = initial ?? null; this.id = id ?? number.generate(1, 10000000); } /** * Send Data to each Subscriber (and listener) * @since 9.0.0 */ async send(type, data, prettify = false) { for (const listener of this.listeners) { await Promise.resolve(listener(data)); } if (this.onPublish) try { const parsed = (await parseContent(data, prettify)).content; if (this.onPublish) this.onPublish(type, parsed); } catch { } this.data = data; return this; } /** * Get the last sent value * @since 9.0.0 */ last() { return as(this.data); } /** * Listen for send events on this Channel * @since 9.0.0 */ listen(callback) { this.listeners.push(callback); return () => { const res = array.remove(this.listeners, 'value', callback); this.listeners.length = 0; this.listeners.push(...res); }; } }