From f11297d5cd0dc06d0f7ed5b43cf1b5d939596b7a Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Sun, 8 Oct 2023 23:31:35 -0400 Subject: [PATCH] feat: add subscribeToUpdates method to listen for updates --- src/index.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/index.ts b/src/index.ts index c52612b..cbb745d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,13 +1,19 @@ import { ActiveQuery, addHandler } from "@lumeweb/libkernel/module"; +import { EventEmitter } from "events"; const types: Set = new Set(); const networks: Map> = new Map>(); +const events = new EventEmitter(); + addHandler("registerType", handleRegisterType); addHandler("getTypes", handleGetTypes); addHandler("getNetworkTypes", handleGetNetworkTypes); addHandler("getNetworksByType", handleGetNetworksByType); addHandler("registerNetwork", handleRegisterNetwork); +addHandler("subscribeToUpdates", handleSubscribeToUpdates, { + receiveUpdates: true, +}); function handleRegisterType(aq: ActiveQuery) { types.add(aq.callerInput); @@ -38,6 +44,8 @@ function handleRegisterNetwork(aq: ActiveQuery) { networks.set(aq.domain, new Set([...aq.callerInput.types])); } + events.emit("update"); + aq.respond(); } @@ -76,3 +84,16 @@ function handleGetNetworksByType(aq: ActiveQuery) { .map((item) => item[0]), ); } + +function handleSubscribeToUpdates(aq: ActiveQuery) { + const cb = () => { + aq.sendUpdate(); + }; + + events.on("update", cb); + + aq.setReceiveUpdate?.(() => { + events.off("update", cb); + aq.respond(); + }); +}