I have a couple repositories
containing database calls such as getUser
and getUsers
.
Now I export those repositories as followed:
import { DatabaseBackend } from "../common/database";
import {
userRepository as _userRepository,
bookingRepository as _bookingRepository,
pricingRepository as _pricingRepository,
} from "../common/repositories";
const backend = DatabaseBackend.ReactNative;
export const userRepository = _userRepository(backend);
export const bookingRepository = _bookingRepository(backend);
export const pricingRepository = _pricingRepository(backend);
This leads to me having to do things like this:
const fetchUserData = (uid: string) => {
userRepository
.then((u) => {
u.getUser(uid)
.then((user: User) => {
if(!user) {
return;
}
setUser(user);
})
.catch((err) => {
logger.error("Something went wrong while fetching user information", err);
});
})
.catch(err => {
logger.error("Something went wrong while fetching user information", err);
});
};
The intellisense says userRepository
is:
const userRepository: Promise<{
getUser: (id: string) => Promise<User>;
getNanny: (id: string) => Promise<Nanny>;
getNannies: () => Promise<Nanny[]>;
getParent: (id: string) => Promise<Parent>;
updateUser: (user: User) => Promise<void>;
}>
Is there a way how to assign the functions to userRepository
without me having to do any then
calls on it? I’d like to just being able to call userRepository.getUser()
for example.
2
Answers
You can use async/await instead of
then
.userRepository
coming from a Promise => try and have this resolved on some initialization phase of at least have memoization on its’ value.async/ await
as suggested here already.