From 09b7e1f737659d0ee75e5ac2fd5c1decf8fa15a6 Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 4 Aug 2020 02:31:59 +0800 Subject: ... --- Timeline/ClientApp/src/app/data/user.ts | 52 ++++++++++----------------------- 1 file changed, 16 insertions(+), 36 deletions(-) (limited to 'Timeline/ClientApp/src/app/data/user.ts') diff --git a/Timeline/ClientApp/src/app/data/user.ts b/Timeline/ClientApp/src/app/data/user.ts index dec9929f..7d522b26 100644 --- a/Timeline/ClientApp/src/app/data/user.ts +++ b/Timeline/ClientApp/src/app/data/user.ts @@ -19,8 +19,6 @@ import { HttpUser, } from '../http/user'; -import { BlobWithUrl } from './common'; - export type User = HttpUser; export interface UserAuthInfo { @@ -230,27 +228,16 @@ export function checkLogin(): UserWithToken { export class UserNotExistError extends Error {} -export type AvatarInfo = BlobWithUrl; - export class UserInfoService { - private _avatarSubscriptionHub = new SubscriptionHub< - string, - AvatarInfo | null - >( - (key) => key, - () => null, - async (key) => { - const blob = (await getHttpUserClient().getAvatar(key)).data; - const url = URL.createObjectURL(blob); - return { - blob, - url, - }; + private _avatarSubscriptionHub = new SubscriptionHub({ + setup: (key, next) => { + void getHttpUserClient() + .getAvatar(key) + .then((res) => { + next(res.data); + }); }, - (_key, data) => { - if (data != null) URL.revokeObjectURL(data.url); - } - ); + }); getUserInfo(username: string): Observable { return from(getHttpUserClient().get(username)).pipe( @@ -261,40 +248,33 @@ export class UserInfoService { async setAvatar(username: string, blob: Blob): Promise { const user = checkLogin(); await getHttpUserClient().putAvatar(username, blob, user.token); - this._avatarSubscriptionHub.update(username, () => - Promise.resolve({ - blob, - url: URL.createObjectURL(blob), - }) - ); + this._avatarSubscriptionHub.update(username, blob); } - get avatarHub(): ISubscriptionHub { + get avatarHub(): ISubscriptionHub { return this._avatarSubscriptionHub; } } export const userInfoService = new UserInfoService(); -export function useAvatarUrl(username?: string): string | undefined { - const [avatarUrl, setAvatarUrl] = React.useState( - undefined - ); +export function useAvatar(username?: string): Blob | undefined { + const [state, setState] = React.useState(undefined); React.useEffect(() => { if (username == null) { - setAvatarUrl(undefined); + setState(undefined); return; } const subscription = userInfoService.avatarHub.subscribe( username, - (info) => { - setAvatarUrl(info?.url); + (blob) => { + setState(blob); } ); return () => { subscription.unsubscribe(); }; }, [username]); - return avatarUrl; + return state; } -- cgit v1.2.3