From 1087499e6cbbee1a506fcd7c762703b90526a7ab Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 6 Aug 2020 23:33:47 +0800 Subject: Avatar use cache first. --- Timeline/ClientApp/src/app/data/user.ts | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) (limited to 'Timeline/ClientApp/src') diff --git a/Timeline/ClientApp/src/app/data/user.ts b/Timeline/ClientApp/src/app/data/user.ts index e893a6c0..14f4e943 100644 --- a/Timeline/ClientApp/src/app/data/user.ts +++ b/Timeline/ClientApp/src/app/data/user.ts @@ -19,6 +19,7 @@ import { HttpUserNotExistError, HttpUser, } from '../http/user'; +import { queue } from './queue'; export type User = HttpUser; @@ -235,8 +236,22 @@ export class UserInfoService { return `user.${username}.avatar`; } + private getCachedAvatar(username: string): Promise { + return dataStorage + .getItem(this.getAvatarKey(username)) + .then((data) => data?.data ?? null); + } + private async fetchAndCacheAvatar( username: string + ): Promise<{ data: Blob; type: 'synced' | 'cache' } | 'offline'> { + return queue(`UserService.fetchAndCacheAvatar.${username}`, () => + this.doFetchAndCacheAvatar(username) + ); + } + + private async doFetchAndCacheAvatar( + username: string ): Promise<{ data: Blob; type: 'synced' | 'cache' } | 'offline'> { const key = this.getAvatarKey(username); const cache = await dataStorage.getItem(key); @@ -286,10 +301,19 @@ export class UserInfoService { private _avatarSubscriptionHub = new SubscriptionHub({ setup: (key, line) => { - void getHttpUserClient() - .getAvatar(key) - .then((res) => { - line.next(res.data); + void this.getCachedAvatar(key) + .then((avatar) => { + if (avatar != null) { + line.next(avatar); + } + }) + .then(() => { + return this.fetchAndCacheAvatar(key); + }) + .then((result) => { + if (result !== 'offline') { + line.next(result.data); + } }); }, }); -- cgit v1.2.3