UNPKG

1.37 kBJavaScriptView Raw
1import { getCollection } from "./collection.js";
2import { getServices } from "./commands.js";
3function processServiceRegistered(state, event) {
4 if (state === undefined)
5 return null;
6 const { domain, service } = event.data;
7 const domainInfo = Object.assign({}, state[domain], {
8 [service]: { description: "", fields: {} }
9 });
10 return { [domain]: domainInfo };
11}
12function processServiceRemoved(state, event) {
13 if (state === undefined)
14 return null;
15 const { domain, service } = event.data;
16 const curDomainInfo = state[domain];
17 if (!curDomainInfo || !(service in curDomainInfo))
18 return null;
19 const domainInfo = {};
20 Object.keys(curDomainInfo).forEach(sKey => {
21 if (sKey !== service)
22 domainInfo[sKey] = curDomainInfo[sKey];
23 });
24 return { [domain]: domainInfo };
25}
26const fetchServices = (conn) => getServices(conn);
27const subscribeUpdates = (conn, store) => Promise.all([
28 conn.subscribeEvents(store.action(processServiceRegistered), "service_registered"),
29 conn.subscribeEvents(store.action(processServiceRemoved), "service_removed")
30]).then(unsubs => () => unsubs.forEach(fn => fn()));
31const servicesColl = (conn) => getCollection(conn, "_srv", fetchServices, subscribeUpdates);
32export const subscribeServices = (conn, onChange) => servicesColl(conn).subscribe(onChange);