Saturday 17 December 2016

How to standardize response objects across my endpoints

Hello.I'm just learning about nodejs and setting up my first project to get acquainted with it. Love what I'm experiencing so far.The website I'm building has a number of different endpoints that can be hit with GET or POST requests to do some operations and return some information. I have a js file where routes access my different collections of operations and return the response from those operations.What I have is working, but it is very clumsy - I have to remember what different fields are called in the responses and it is hard to handle error cases correctly.The pattern I'd like to follow is, every GET or POST request should return object with three fields - message, success, and data. Message will carry a simple explanation, this will be useful in an error case. Success will be a boolean representing whether or not the request succeeded. I'm imagining several operations where the user will attempt something, and if the attempt failed then the message from the response will be displayed to the user. Finally, the data field should contain the usable data if the operation succeeded.Is there a way I can force my routes to follow this pattern? Is there a way I can cleanly implement this kind of behavior without having to write something like "res.send({"message": "example problem", "success": false, data: {}})" in every case where I'd be sending a response?I'd also be interested in the commonly accepted pattern for handling cases like this.

Submitted December 17, 2016 at 08:22AM by electricfistula

No comments:

Post a Comment