I'm learning Node.js and I have a problem with code refactoring. I read about the code architecture in Node.js and good coding practice and I want to refactor my code.
My current code:
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.'
})
});
});
}
I want to put all business logic into services. I tried something like this:
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);
});
});
}
But I get many errors about promise:
(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.
I'm newbie in Node.js and JavaScript. How to fix this?