UNPKG

1.06 kBJavaScriptView Raw
1import { getCollection } from "./collection.js";
2import { getStates } from "./commands.js";
3function processEvent(store, event) {
4 const state = store.state;
5 if (state === undefined)
6 return;
7 const { entity_id, new_state } = event.data;
8 if (new_state) {
9 store.setState({ [new_state.entity_id]: new_state });
10 }
11 else {
12 const newEntities = Object.assign({}, state);
13 delete newEntities[entity_id];
14 store.setState(newEntities, true);
15 }
16}
17async function fetchEntities(conn) {
18 const states = await getStates(conn);
19 const entities = {};
20 for (let i = 0; i < states.length; i++) {
21 const state = states[i];
22 entities[state.entity_id] = state;
23 }
24 return entities;
25}
26const subscribeUpdates = (conn, store) => conn.subscribeEvents(ev => processEvent(store, ev), "state_changed");
27export const entitiesColl = (conn) => getCollection(conn, "_ent", fetchEntities, subscribeUpdates);
28export const subscribeEntities = (conn, onChange) => entitiesColl(conn).subscribe(onChange);