在Node.js中将业务逻辑从控制器重构为服务



我正在学习Node.js,我在代码重构方面遇到了问题。我阅读了Node.js中的代码体系结构和良好的编码实践,我想重构我的代码。

我当前的代码:

user.controller.js

const bcrypt = require('bcryptjs');
const User = require('../models/user');
exports.createUser = (req, res, next) => {
bcrypt.hash(req.body.password, 10)
.then(hash => {
const user = new User({
email: req.body.email,
password: hash
});
user.save()
.then(result => {
res.status(201).json({
message: 'User created!',
result: result
})
})
.catch(err => {
res.status(400).json({
message: 'An unknown error has occurred.'
})
});
});
}

我想把所有的业务逻辑都放到服务中。我试过这样的东西:

user.controller.js

const UserService = require('../services/user.service');
exports.createUser = async function (req, res, next) {
try {
var result = await UserService.createUser(req.body.email, req.body.password);
return res.status(200).json({ result: result, message: "User created!" });
} catch (e) {
return res.status(400).json({ message: e.message });
}
}

user.service.js

const bcrypt = require('bcryptjs');
const User = require('../models/user.model');
exports.createUser = async function (email, password) {
bcrypt.hash(password, 10)
.then(hash => {
const user = new User({
email: email,
password: hash
});
user.save()
.then(result => {
return result;
})
.catch(err => {
throw new Error(err);
});
});
}

但我收到了许多关于承诺的错误:

(node:3760) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not ha
ndled with .catch(). (rejection id: 1)
(node:3760) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我是Node.js和JavaScript的新手。如何解决此问题?

如果您希望tu使用promise,请在编码一致性很高时使用promise。如果您想使用async await(promise的语法糖(,请处处使用async wait。

Promise在末尾使用链式捕获来处理错误。

MyPromise().then(() => bar).catch((err) =>  do something with err )

对于async/await,您应该放置一个

try { } catch (err) {}

在您的情况下,它只是说在任何包含promise的异步函数中,您都应该用try-catch来包装它们。

希望能有所帮助。我的最后一个建议是先学一种方法,然后再学另一种方法——不要把它们混在一起。

感谢您的回答。我修改了我的代码,现在看起来像这样:

user.controller.js

const UserService = require('../services/user.service');
exports.createUser = async function (req, res, next) {
try {
let user = await UserService.createUser(req.body.email, req.body.password);
return res.status(201).json({ data: user, message: 'User created!' });
} catch (e) {
let errorMsg;
let statusCode;
if(e.errors['email'].kind === 'unique') {
statusCode = 422;
errorMsg = 'E-mail already exists.';
} else {
statusCode = 500;
errorMsg = 'An unknown error has occurred.';
}
return res.status(statusCode).json({ message: errorMsg });
}
}

user.service.js

const bcrypt = require('bcryptjs');
const User = require('../models/user.model');
exports.createUser = async function (email, password) {
const hash = bcrypt.hashSync(password, 10);
const user = new User({
email: email,
password: hash
});
await user.save();
return result;
}

我的代码正确吗?我说的是编码体系结构。工作正常,但我不确定我的代码是否是"良好实践"编程。我这么问是因为我想开始写整个后端,但我不确定我的代码。

我认为这部分代码看起来不太好:

} catch (e) {
let errorMsg;
let statusCode;
if(e.errors['email'].kind === 'unique') {
statusCode = 422;
errorMsg = 'E-mail already exists.';
} else {
statusCode = 500;
errorMsg = 'An unknown error has occurred.';
}
return res.status(statusCode).json({ message: errorMsg });
}

例如,在其他控制器中,我会有5If语句。这是正确的解决方案吗?我正在寻求建议,可以在这里更改什么以使代码专业化。

最新更新