feat: add subscribeToUpdates method to listen for updates

This commit is contained in:
Derrick Hammer 2023-10-08 23:31:35 -04:00
parent 78c02b260b
commit f11297d5cd
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 21 additions and 0 deletions

View File

@ -1,13 +1,19 @@
import { ActiveQuery, addHandler } from "@lumeweb/libkernel/module"; import { ActiveQuery, addHandler } from "@lumeweb/libkernel/module";
import { EventEmitter } from "events";
const types: Set<string> = new Set<string>(); const types: Set<string> = new Set<string>();
const networks: Map<string, Set<string>> = new Map<string, Set<string>>(); const networks: Map<string, Set<string>> = new Map<string, Set<string>>();
const events = new EventEmitter();
addHandler("registerType", handleRegisterType); addHandler("registerType", handleRegisterType);
addHandler("getTypes", handleGetTypes); addHandler("getTypes", handleGetTypes);
addHandler("getNetworkTypes", handleGetNetworkTypes); addHandler("getNetworkTypes", handleGetNetworkTypes);
addHandler("getNetworksByType", handleGetNetworksByType); addHandler("getNetworksByType", handleGetNetworksByType);
addHandler("registerNetwork", handleRegisterNetwork); addHandler("registerNetwork", handleRegisterNetwork);
addHandler("subscribeToUpdates", handleSubscribeToUpdates, {
receiveUpdates: true,
});
function handleRegisterType(aq: ActiveQuery) { function handleRegisterType(aq: ActiveQuery) {
types.add(aq.callerInput); types.add(aq.callerInput);
@ -38,6 +44,8 @@ function handleRegisterNetwork(aq: ActiveQuery) {
networks.set(aq.domain, new Set([...aq.callerInput.types])); networks.set(aq.domain, new Set([...aq.callerInput.types]));
} }
events.emit("update");
aq.respond(); aq.respond();
} }
@ -76,3 +84,16 @@ function handleGetNetworksByType(aq: ActiveQuery) {
.map((item) => item[0]), .map((item) => item[0]),
); );
} }
function handleSubscribeToUpdates(aq: ActiveQuery) {
const cb = () => {
aq.sendUpdate();
};
events.on("update", cb);
aq.setReceiveUpdate?.(() => {
events.off("update", cb);
aq.respond();
});
}