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,
});
});
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);