I am writing an application in Express.js with a separate controller layer and a service layer.
(我正在Express.js中编写一个具有单独的控制器层和服务层的应用程序。)
Here is my current code:(这是我当前的代码:)
user.service.js
(user.service.js)
exports.registerUser = async function (email, password) {
const hash = await bcrypt.hash(password, 10);
const countUser = await User.countDocuments({email: email});
if(countUser > 0) {
throw ({ status: 409, code: 'USER_ALREADY_EXISTS', message: 'This e-mail address is already taken.' });
}
const user = new User({
email: email,
password: hash
});
return await user.save();
};
exports.loginUser = async function (email, password) {
const user = await User.findOne({ email: email });
const countUser = await User.countDocuments({email: email});
if(countUser === 0) {
throw ({ status: 404, code: 'USER_NOT_EXISTS', message: 'E-mail address does not exist.' });
}
const validPassword = await bcrypt.compare(password, user.password);
if (validPassword) {
const token = jwt.sign({ email: user.email, userId: user._id }, process.env.JWT_KEY, { expiresIn: "10s" });
return {
token: token,
expiresIn: 3600,
userId: user._id
}
} else {
throw ({ status: 401, code: 'LOGIN_INVALID', message: 'Invalid authentication credentials.' });
}
};
user.controller.js
(user.controller.js)
exports.userRegister = async function (req, res, next) {
try {
const user = await UserService.registerUser(req.body.email, req.body.password);
res.status(201).json({ data: user });
} catch (e) {
if(!e.status) {
res.status(500).json( { error: { code: 'UNKNOWN_ERROR', message: 'An unknown error occurred.' } });
} else {
res.status(e.status).json( { error: { code: e.code, message: e.message } });
}
}
}
exports.userLogin = async function (req, res, next) {
try {
const user = await UserService.loginUser(req.body.email, req.body.password);
res.status(200).json({ data: user });
} catch (e) {
if(!e.status) {
res.status(500).json( { error: { code: 'UNKNOWN_ERROR', message: 'An unknown error occurred.' } });
} else {
res.status(e.status).json( { error: { code: e.code, message: e.message } });
}
}
}
The code works, but requires some corrections.
(该代码有效,但需要进行一些更正。)
I have a problem with error handling.(我有一个错误处理问题。)
I want to handle only some errors.(我只想处理一些错误。)
If another error has occurred, the 500 Internal Server Error will be returned.(如果发生另一个错误,将返回500 Internal Server Error。)
1) Can I use "throw" object from the service layer?
(1)我可以使用服务层中的“抛出”对象吗?)
Is this a good practice?(这是一个好习惯吗?)
2) How to avoid duplication of this code in each controller:
(2)如何避免在每个控制器中重复此代码:)
if(!e.status) {
res.status(500).json( { error: { code: 'UNKNOWN_ERROR', message: 'An unknown error occurred.' } });
} else {
res.status(e.status).json( { error: { code: e.code, message: e.message } });
}
3) Does the code require other corrections?
(3)代码是否需要其他更正?)
I'm just learning Node.js and I want to write the rest of the application well.(我只是在学习Node.js,我想很好地编写应用程序的其余部分。)
ask by Wojtek Szymczyk translate from so