feat: add subscribeToUpdates method to listen for updates
This commit is contained in:
parent
78c02b260b
commit
f11297d5cd
21
src/index.ts
21
src/index.ts
|
@ -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();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue