From 6c7b73e7aa65a3b250144fbf59a4053e9c9d02e7 Mon Sep 17 00:00:00 2001 From: Andrey Mikhadyuk Date: Thu, 30 Nov 2023 16:38:56 +0400 Subject: [PATCH] add changes to cached user update to load it on error --- src/services/User.ts | 60 +++++++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 18 deletions(-) diff --git a/src/services/User.ts b/src/services/User.ts index 4e30a21f4b..18c7664f31 100644 --- a/src/services/User.ts +++ b/src/services/User.ts @@ -15,7 +15,6 @@ import { convertObjectDatesToFirestoreTimestamps, convertToTimestamp, firestoreDataConverter, - transformFirebaseDataList, } from "@/shared/utils"; import firebase from "@/shared/utils/firebase"; import * as cacheActions from "@/store/states/cache/actions"; @@ -51,31 +50,56 @@ class UserService { }; }; - public getUserById = async (userId: string): Promise => { - const userSnapshot = await this.getUsersCollection() + public getUserById = async ( + userId: string, + cached = false, + ): Promise => { + const snapshot = await this.getUsersCollection() .where("uid", "==", userId) - .get(); + .get({ source: cached ? "cache" : "default" }); + const users = snapshot.docs.map((doc) => doc.data()); + const user = users[0] || null; + + if (cached && !user) { + return this.getUserById(userId); + } - return transformFirebaseDataList(userSnapshot)[0] || null; + return user; }; public getCachedUserById = async (userId: string): Promise => { - const userState = store.getState().cache.userStates[userId]; + try { + const userState = store.getState().cache.userStates[userId]; - if (userState?.fetched) { - return userState.data; - } - if (userState?.loading) { - return await waitForUserToBeLoaded(userId); - } + if (userState?.fetched) { + return userState.data; + } + if (userState?.loading) { + return await waitForUserToBeLoaded(userId); + } - store.dispatch( - cacheActions.getUserStateById.request({ - payload: { userId }, - }), - ); + store.dispatch( + cacheActions.getUserStateById.request({ + payload: { userId }, + }), + ); + + return await waitForUserToBeLoaded(userId); + } catch (err) { + const user = await this.getUserById(userId, true); + store.dispatch( + cacheActions.updateUserStateById({ + userId, + state: { + loading: false, + fetched: true, + data: user, + }, + }), + ); - return await waitForUserToBeLoaded(userId); + return user; + } }; public getCachedUsersById = async (userIds: string[]): Promise =>