I'm looking to enhance my Node JS skills by improving the way I separate the service and router layers in my applications. I want to avoid code duplication, like in the case of the create method
for a user scheme.
In my UserService.Js
file, I have the following method:
function createUser(req, res, next) {
let user = new User({
userID: req.body.userID,
userName: req.body.userName,
password: req.body.password,
isAdministrator: req.body.isAdministrator
});
user.save().then(function() {
res.send(user);
}).catch(err => {
console.log(err);
});
}
The code in UserRouter.Js
connects this method:
router.post('/publicUser', userService.createUser)
Although it functions correctly, the separation of concerns could be improved. What's the best way to rewrite the create function using a callback function?
My revised version is as follows:
UserService.js
function createUser() {
let user = new User
return user;
}
UserRoute.js
router.post('/publicUser', function(req, res, next){
let newUser = userService.createUser()
newUser.userID = req.body.userID
newUser.userName = req.body.userName
newUser.password = req.body.password
newUser.isAdministrator = req.body.isAdministrator
newUser.save().then(function() {
res.send(newUser);
}).catch(err => {
console.log(err);
})})
This updated approach works well, but I wonder if there is a more elegant solution available?