mizzkey/src/client/sw/notification-read.ts

61 lines
1.5 KiB
TypeScript
Raw Normal View History

declare var self: ServiceWorkerGlobalScope;
2021-02-10 22:30:02 +09:00
import { get } from 'idb-keyval';
2021-02-10 22:19:09 +09:00
import { pushNotificationData } from '../../types';
type Accounts = {
2021-02-10 22:30:02 +09:00
[x: string]: {
queue: string[],
timeout: number | null,
token: string,
}
2021-02-10 22:19:09 +09:00
};
class SwNotificationRead {
private accounts: Accounts = {};
2021-02-10 22:30:02 +09:00
public async construct() {
const accounts = await get('accounts') as { i: string, id: string }[];
if (accounts) Error('Account is not recorded');
2021-02-10 22:19:09 +09:00
this.accounts = accounts.reduce((acc, e) => {
2021-02-10 22:30:02 +09:00
acc[e.id] = {
queue: [],
timeout: null,
token: e.i,
};
return acc;
}, {} as Accounts);
return this;
}
2021-02-10 22:19:09 +09:00
// プッシュ通知の既読をサーバーに送信
public async read(data: pushNotificationData) {
2021-02-10 22:30:02 +09:00
if (data.type !== 'notification' || !(data.userId in this.accounts)) return;
2021-02-10 22:19:09 +09:00
2021-02-10 22:30:02 +09:00
const account = this.accounts[data.userId];
2021-02-10 22:19:09 +09:00
2021-02-10 22:30:02 +09:00
account.queue.push(data.body.id);
2021-02-10 22:19:09 +09:00
2021-02-10 22:30:02 +09:00
// 最後の呼び出しから100ms待ってまとめて処理する
2021-02-10 22:19:09 +09:00
if (account.timeout) clearTimeout(account.timeout);
account.timeout = setTimeout(() => {
account.timeout = null;
2021-02-10 22:30:02 +09:00
console.info(account.token, account.queue);
2021-02-10 22:19:09 +09:00
fetch(`${location.origin}/api/notifications/read`, {
method: 'POST',
body: JSON.stringify({
i: account.token,
notificationIds: account.queue
})
}).then(res => {
self.registration.showNotification('notificationread', { body: `${account.queue}, ${res.ok}` });
2021-02-10 22:19:09 +09:00
});
}, 100);
}
}
export const swNotificationRead = (new SwNotificationRead()).construct();