I am curious about incorporating CRUD operations as callbacks while maintaining the Separation of Concerns.
For instance, I have written a function that retrieves all users:
UserService.js
function getUsers(callback) {
User.find(function(err, users) {
if (err) {
console.log("Error during search: " + err)
return callback(err, null)
}
console.log("All went well.");
return callback(null, users);
})
}
UserRoute.js
router.get('/publicUser', function(req, res, next) {
userService.getUsers(function(err, result) {
console.log("Result: " + result)
if (result) {
res.send(Object.values(result))
} else {
res.send("There were issues.")
}
})
})
In my opinion, a corresponding CRUD function that returns exactly one user without using a callback would look like this:
Userservice.js
function getByUserId(req, res, next) {
let userID = req.body.userID;
User.findOne({
userID: userID
}, function(err, result) {
if (err) {
console.log("Error during search: " + err)
} else {
console.log("All went well.");
res.send(result)
}
})
}
UserRoute.js
router.post('/publicUser/getByUserID', userService.getByUserId)
What would the same function look like when using a callback?