Skip to content

Commit

Permalink
add changes to cached user update to load it on error
Browse files Browse the repository at this point in the history
  • Loading branch information
andreymikhadyuk committed Nov 30, 2023
1 parent c7556b0 commit 6c7b73e
Showing 1 changed file with 42 additions and 18 deletions.
60 changes: 42 additions & 18 deletions src/services/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -51,31 +50,56 @@ class UserService {
};
};

public getUserById = async (userId: string): Promise<User | null> => {
const userSnapshot = await this.getUsersCollection()
public getUserById = async (
userId: string,
cached = false,
): Promise<User | null> => {
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<User>(userSnapshot)[0] || null;
return user;
};

public getCachedUserById = async (userId: string): Promise<User | null> => {
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<User[]> =>
Expand Down

0 comments on commit 6c7b73e

Please sign in to comment.