This commit is contained in:
tamaina
2021-02-15 06:05:18 +09:00
parent a8c4c74954
commit bf1db27824
15 changed files with 435 additions and 169 deletions

View File

@@ -2,12 +2,12 @@ declare var self: ServiceWorkerGlobalScope;
import { get } from 'idb-keyval';
import { pushNotificationData } from '../../types';
import { api } from './operations';
type Accounts = {
[x: string]: {
queue: string[],
timeout: number | null,
token: string,
timeout: number | null
}
};
@@ -15,14 +15,13 @@ class SwNotificationRead {
private accounts: Accounts = {};
public async construct() {
const accounts = await get('accounts') as { token: string, id: string }[];
if (!accounts) Error('Account is not recorded');
const accounts = await get('accounts');
if (!accounts) Error('Accounts are not recorded');
this.accounts = accounts.reduce((acc, e) => {
acc[e.id] = {
queue: [],
timeout: null,
token: e.token,
timeout: null
};
return acc;
}, {} as Accounts);
@@ -36,21 +35,14 @@ class SwNotificationRead {
const account = this.accounts[data.userId];
account.queue.push(data.body.id);
account.queue.push(data.body.id as string);
// 最後の呼び出しから200ms待ってまとめて処理する
if (account.timeout) clearTimeout(account.timeout);
account.timeout = setTimeout(() => {
account.timeout = null;
console.info(account.token, account.queue);
fetch(`${location.origin}/api/notifications/read`, {
method: 'POST',
body: JSON.stringify({
i: account.token,
notificationIds: account.queue
})
});
api('notifications/read', data.userId, { notificationIds: account.queue });
}, 200);
}
}