Skip to content

Commit

Permalink
Fix removing entity attributes (#251)
Browse files Browse the repository at this point in the history
Co-authored-by: Paulus Schoutsen <[email protected]>
  • Loading branch information
bdraco and balloob authored Mar 12, 2022
1 parent ad452bd commit 99b54f4
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions lib/entities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,16 @@ interface EntityState {
lu: number;
}

interface EntityStateRemove {
/** attributes */
a: string[];
}

interface EntityDiff {
/** additions */
"+"?: Partial<EntityState>;
/** subtractions */
"-"?: Pick<EntityState, "a">;
"-"?: EntityStateRemove;
}

interface StatesUpdates {
Expand Down Expand Up @@ -80,6 +85,10 @@ function processEvent(store: Store<HassEntities>, updates: StatesUpdates) {
entityState = { ...entityState };

const { "+": toAdd, "-": toRemove } = updates.c[entityId];
const attributesChanged = toAdd?.a || toRemove?.a;
const attributes = attributesChanged
? { ...entityState.attributes }
: entityState.attributes;

if (toAdd) {
if (toAdd.s) {
Expand All @@ -100,17 +109,17 @@ function processEvent(store: Store<HassEntities>, updates: StatesUpdates) {
entityState.last_updated = new Date(toAdd.lu * 1000).toISOString();
}
if (toAdd.a) {
entityState.attributes = { ...entityState.attributes, ...toAdd.a };
Object.assign(attributes, toAdd.a);
}
}
if (toRemove) {
const attributes = { ...entityState.attributes };
for (const key in toRemove.a) {
if (toRemove?.a) {
for (const key of toRemove.a) {
delete attributes[key];
}
}
if (attributesChanged) {
entityState.attributes = attributes;
}

state[entityId] = entityState;
}
}
Expand Down

0 comments on commit 99b54f4

Please sign in to comment.