He estado tratando de refactorizar el código a continuación para que sea modular y pueda seguir el DRY, pero estoy luchando para implementar la parte req.body. ¿Cómo puedo refactorizar estas dos piezas de código en una modular?
Primera pieza de código
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, }); });
Segunda pieza de código
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, }); });
Puede hacer que la identificación y el objeto sean genéricos en su código y pasarlos como argumentos:
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);