Friday 18 January 2019

Refactoring Controllers (Route Handlers)

Hi all,In the context of nodejs backend API applications, is it accurate to say that controllers(route handlers) have the following responsibilities (and nothing more):Extract the parameters (query or body) from the requestCall external functions to perform backend operationsReturn an HTTP response (with status code and serialized data)In the past, I have (admittedly with lack of foresight), done something of the following nature:function createUserController(req, res, next) { const userName = req.body.name // perform CRUD operations with an ORM User.create(userName) .then(function() { res.status(200).end(); }) .catch(function() { res.status(400).end(); }) } Aside from a bloated controller, I end up having express related objects passed down to data layers (as stipulated here: https://github.com/i0natan/nodebestpractices#-12-layer-your-components-keep-express-within-its-boundaries), which also makes it more difficult to unit test.To remedy this issue, what do you think of the following implementation:// Controller function createUserController(req, res, next) { const userName = req.body.name // perform CRUD operations with an ORM userDataOperations = new UserDataOperations(); userDataOperations .on('SUCCESS', function() { res.status(200).end() }) .on('ERROR', function() { res.status(400).end() }) userDataOperations.saveUser(userName); } // CRUD operations class UserDataOperations extends EventEmitter { saveUser(userName) { User.create(userName) .then(function() { this.emit('SUCCESS') }) .catch(function() { this.emit('ERROR') }) } } Have you guys experienced any issues with an EventEmitter implementation? How would you generally approach this?

Submitted January 18, 2019 at 10:06PM by raccoonranger73

No comments:

Post a Comment