Complete persistent notifications migration (#16476)

* Complete migration of persistent notifications

* Complete migration of persistent notifications

* revert
This commit is contained in:
J. Nick Koston 2023-05-25 22:09:04 -05:00 committed by GitHub
parent fba12f35ac
commit 77d1b19ecb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,7 +1,7 @@
import { import {
Connection, Connection,
createCollection,
HassEntity, HassEntity,
UnsubscribeFunc,
} from "home-assistant-js-websocket"; } from "home-assistant-js-websocket";
export interface PersitentNotificationEntity extends HassEntity { export interface PersitentNotificationEntity extends HassEntity {
@ -19,25 +19,52 @@ export interface PersistentNotification {
status: "read" | "unread"; status: "read" | "unread";
} }
const fetchNotifications = (conn) => export interface PersistentNotifications {
conn.sendMessagePromise({ [notificationId: string]: PersistentNotification;
type: "persistent_notification/get", }
});
const subscribeUpdates = (conn, store) => export interface PersistentNotificationMessage {
conn.subscribeEvents( type: "added" | "removed" | "current" | "updated";
() => fetchNotifications(conn).then((ntf) => store.setState(ntf, true)), notifications: PersistentNotifications;
"persistent_notifications_updated" }
);
export const subscribeNotifications = ( export const subscribeNotifications = (
conn: Connection, conn: Connection,
onChange: (notifications: PersistentNotification[]) => void onChange: (notifications: PersistentNotification[]) => void
) => ): UnsubscribeFunc => {
createCollection<PersistentNotification[]>( const params = {
"_ntf", type: "persistent_notification/subscribe",
fetchNotifications, };
subscribeUpdates, const stream = new NotificationStream();
conn, const subscription = conn.subscribeMessage<PersistentNotificationMessage>(
onChange (message) => onChange(stream.processMessage(message)),
params
); );
return () => {
subscription.then((unsub) => unsub?.());
};
};
class NotificationStream {
notifications: PersistentNotifications;
constructor() {
this.notifications = {};
}
processMessage(
streamMessage: PersistentNotificationMessage
): PersistentNotification[] {
if (streamMessage.type === "removed") {
for (const notificationId of Object.keys(streamMessage.notifications)) {
delete this.notifications[notificationId];
}
} else {
this.notifications = {
...this.notifications,
...streamMessage.notifications,
};
}
return Object.values(this.notifications);
}
}