2022-04-30 12:52:07 +00:00
|
|
|
declare var self: ServiceWorkerGlobalScope;
|
|
|
|
|
2023-01-13 04:40:33 +00:00
|
|
|
import { get } from "idb-keyval";
|
|
|
|
import { pushNotificationDataMap } from "@/types";
|
|
|
|
import { api } from "@/scripts/operations";
|
2022-04-30 12:52:07 +00:00
|
|
|
|
|
|
|
type Accounts = {
|
|
|
|
[x: string]: {
|
2023-01-13 04:40:33 +00:00
|
|
|
queue: string[];
|
|
|
|
timeout: number | null;
|
|
|
|
};
|
2022-04-30 12:52:07 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
class SwNotificationReadManager {
|
|
|
|
private accounts: Accounts = {};
|
|
|
|
|
|
|
|
public async construct() {
|
2023-01-13 04:40:33 +00:00
|
|
|
const accounts = await get("accounts");
|
|
|
|
if (!accounts) Error("Accounts are not recorded");
|
2022-04-30 12:52:07 +00:00
|
|
|
|
|
|
|
this.accounts = accounts.reduce((acc, e) => {
|
|
|
|
acc[e.id] = {
|
|
|
|
queue: [],
|
2023-01-13 04:40:33 +00:00
|
|
|
timeout: null,
|
2022-04-30 12:52:07 +00:00
|
|
|
};
|
|
|
|
return acc;
|
|
|
|
}, {} as Accounts);
|
|
|
|
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
// プッシュ通知の既読をサーバーに送信
|
2023-01-13 04:40:33 +00:00
|
|
|
public async read<K extends keyof pushNotificationDataMap>(
|
|
|
|
data: pushNotificationDataMap[K],
|
|
|
|
) {
|
|
|
|
if (data.type !== "notification" || !(data.userId in this.accounts)) return;
|
2022-04-30 12:52:07 +00:00
|
|
|
|
|
|
|
const account = this.accounts[data.userId];
|
|
|
|
|
|
|
|
account.queue.push(data.body.id as string);
|
|
|
|
|
2022-06-12 10:28:13 +00:00
|
|
|
if (account.queue.length >= 20) {
|
|
|
|
if (account.timeout) clearTimeout(account.timeout);
|
|
|
|
const notificationIds = account.queue;
|
|
|
|
account.queue = [];
|
2023-01-13 04:40:33 +00:00
|
|
|
await api("notifications/read", data.userId, { notificationIds });
|
2022-06-12 10:28:13 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-04-30 12:52:07 +00:00
|
|
|
// 最後の呼び出しから200ms待ってまとめて処理する
|
|
|
|
if (account.timeout) clearTimeout(account.timeout);
|
|
|
|
account.timeout = setTimeout(() => {
|
|
|
|
account.timeout = null;
|
|
|
|
|
2022-06-12 10:28:13 +00:00
|
|
|
const notificationIds = account.queue;
|
|
|
|
account.queue = [];
|
2023-01-13 04:40:33 +00:00
|
|
|
api("notifications/read", data.userId, { notificationIds });
|
2022-04-30 12:52:07 +00:00
|
|
|
}, 200);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-13 04:40:33 +00:00
|
|
|
export const swNotificationRead = new SwNotificationReadManager().construct();
|