skip to Main Content

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


  1. You can use async/await instead of then.

    const fetchUserData = async (uid: string) => {
      try {
        const repo = await userRepository();
        const user: User = await repo.getUser(uid);
        if (!user) {
          return;
        }
        setUser(user);
      } catch (err) {
        logger.error("Something went wrong while fetching user information", err);
      }
    };
    
    Login or Signup to reply.
    1. i would try and avoid having the userRepository coming from a Promise => try and have this resolved on some initialization phase of at least have memoization on its’ value.
    2. use async/ await as suggested here already.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search