Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
Refactor Nodejs controller code function to follow the DRY principle

I have been trying to refactor the code below to be modular and be able to follow the DRY but I am struggling to implement the req.body part. How can I possibly refactor these two pieces of code into one modular one?

First piece of code

exports.chefLogin = catchAsync(async (req, res, next) => {
  const { email, password, restaurantId } = req.body;

  //1) Check if email and password exists
  if (!email || !password || !restaurantId) {
    return next(
      new AppError('Please provide all/Valid login credentials!', 400)
    );
  }
  //2) Check if user exists && password is correct
  const chef = await Chef.findOne({ email, restaurantId }).select('+password');

  if (!chef || !(await chef.correctPassword(password, chef.password))) {
    return next(new AppError('Incorrect email or password or ID', 401));
  }
  //3) If everything is ok , send token to client
  const token = signToken(chef._id);
  res.status(200).json({
    status: 'success',
    token,
    chef,
  });
});

Second Piece of code

exports.deliveryTeamLogin = catchAsync(async (req, res, next) => {
  const { email, password, deliveryTeamId } = req.body;

  //1) Check if email and password exists
  if (!email || !password || !deliveryTeamId) {
    return next(
      new AppError('Please provide all/Valid login credentials!', 400)
    );
  }
  //2) Check if user exists && password is correct
  const deliveryTeamMember = await DeliveryTeam.findOne({
    email,
    deliveryTeamId,
  }).select('+password');

  if (
    !deliveryTeamMember ||
    !(await deliveryTeamMember.correctPassword(
      password,
      deliveryTeamMember.password
    ))
  ) {
    return next(new AppError('Incorrect email or password or ID', 401));
  }
  //3) If everything is ok , send token to client
  const token = signToken(deliveryTeamMember._id);
  res.status(200).json({
    status: 'success',
    token,
    deliveryTeamMember,
  });
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can make the id and object generic in your code and pass them in as arguments:

const login = (id, obj) => catchAsync(async (req, res, next) => {
  const { email, password, [id]: id } = req.body;

  //1) Check if email and password exists
  if (!email || !password || !id) {
    return next(
      new AppError('Please provide all/Valid login credentials!', 400)
    );
  }
  //2) Check if user exists && password is correct
  const login = await obj.findOne({
    email,
    id,
  }).select('+password');

  if (
    !login ||
    !(await login.correctPassword(
      password,
      login.password
    ))
  ) {
    return next(new AppError('Incorrect email or password or ID', 401));
  }
  //3) If everything is ok , send token to client
  const token = signToken(login._id);
  res.status(200).json({
    status: "success",
    token,
    login,
  });
});

exports.chefLogin = login("restaurantId", Chef);
exports.deliveryTeamLogin = login("deliveryTeamId", DeliveryTeam);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda