UNPKG

node-jet

Version:

Jet Realtime Message Bus for the Web. Daemon and Peer implementation.

61 lines (60 loc) 1.84 kB
'use strict'; import { createPathMatcher } from './path_matcher.js'; import { create as createValueMatcher } from './value_matcher.js'; /** A subscription corresponds to a fetch request. * Each subscription contains all the routes that match the subscription */ export class Subscription { owner; id; messages = []; routes = []; pathMatcher; valueMatcher; constructor(msg, peer = undefined) { this.pathMatcher = createPathMatcher(msg); this.valueMatcher = createValueMatcher(msg); this.owner = peer; this.id = msg.id; } close = () => { this.routes.forEach((route) => { route.removeListener('Change', this.handleChange); route.removeListener('Remove', this.handleRemove); }); }; handleChange = (path, value) => { this.enqueue({ path, event: 'Change', value }); }; handleRemove = (path) => { this.enqueue({ path, event: 'Remove' }); }; addRoute = (route) => { this.routes.push(route); if (this.valueMatcher(route.value)) { this.enqueue({ path: route.path, event: 'Add', value: route.value }); } route.addListener('Change', this.handleChange); route.addListener('Remove', this.handleRemove); }; setRoutes = (routes) => { routes.forEach((route) => { this.addRoute(route); }); }; matchesPath = (path) => this.pathMatcher(path); matchesValue = (value) => this.valueMatcher(value); enqueue = (msg) => { this.messages.push(msg); }; send = () => { this.messages.forEach(async (msg) => { await this.owner?.queue(msg, this.id); }); this.owner?.send(); this.messages = []; }; }