diff --git a/materialious/src/lib/thumbnail.ts b/materialious/src/lib/thumbnail.ts index 588aa16a..63d1ee7a 100644 --- a/materialious/src/lib/thumbnail.ts +++ b/materialious/src/lib/thumbnail.ts @@ -2,21 +2,32 @@ import type { Image } from './api/model'; import { localDb } from './dexie'; import { getBestThumbnail } from './images'; +const updateDebounce: Record> = {}; +let isInitial = false; + export async function associateAvatar(channelId: string, avatars: Image[]) { if (avatars.length === 0) return; - await localDb.channelAvatars.put( - { - channelId: channelId, - avatarUrl: getBestThumbnail(avatars), - updated: new Date() - }, - { channelId: channelId } - ); + if ('channelId' in updateDebounce) clearTimeout(updateDebounce[channelId]); - const oneMonthAgo = new Date(); - oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1); - localDb.channelAvatars.where('updated').below(oneMonthAgo).delete(); + updateDebounce[channelId] = setTimeout(() => { + localDb.channelAvatars.put( + { + channelId: channelId, + avatarUrl: getBestThumbnail(avatars), + updated: new Date() + }, + { channelId: channelId } + ); + }, 100); + + if (isInitial) { + isInitial = true; + + const oneMonthAgo = new Date(); + oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1); + localDb.channelAvatars.where('updated').below(oneMonthAgo).delete(); + } } export async function avatarFromChannelId(channelId: string): Promise {