Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda