Generic mongoose model in middleware part of shared library

Viewed 94

I'm building a TypeScript middleware part of a library meant to be shared by multiple microservices. The goal of this middleware is very simple: append the 'role' to req.currentUser. However to do so, I need a db query and each microservice has its own custom User model definition (all contain a role field). How can that be done so that I can still have the middleware live in the common library to avoid copy/pasting code? (Current error is ofc that User is not defined right after the 'try' key word)

export const userRole = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  if (!req.currentUser) {
    const payload: UserPayload = {
      id: '',
      email: '',
      role: userRoles.GUEST_ROLE
    }

    next();
  }

  try {
    // find user by id in the database
    const existingUser = await User.findOne({ id, email }); // How to use whatever User definition exists in each microservice?
    if (!existingUser) {
      throw new BadRequestError("User with given id and email does not exist.");
    }

    // append role to req.currentUser.role
    req.currentUser.role = existingUser.role;

  } catch (err) {/* do logging later */}

  next();
};
0 Answers
Related