user2727195 user2727195 - 5 months ago 9
Node.js Question

Custom property on response object of http

Is there a convention to decorate the

response
object with your own values.

I'm running into a situation where I'm using promises where I could return one value only and I need to return both
body
and
response
object.

I tried to create an object of the form but not happy with it.

resolve({body: body, response: response})


or

response.body = body
resolve(response);


I came across res.locals too for an inspiration.

I wished to find a property on response object that could populate for instance

response.locals = {};
response.locals.body = body
resolve(response);


I tried to lookup a property on
response
object that somehow may have this
body
populated automatically but couldn't. Please advise for the best.

Edit

Sorry if question got confused with expressjs, it's
require('https')
response
object.

Answer

As for promises in general, the usual way of returning multiple values is to either put them in an array and resolve with the array or put them in an object and resolve with the object (as you have done). I don't know exactly why you're unhappy with:

resolve({body: body, response: response})

as that is a typical way to resolve a promise with multiple named values. In ES6, you could even shorten it to:

resolve({body, response})

which is just a syntax shortcut for the same object definition.


With the usual caveat of being careful to avoid property name collisions with standard properties or properties any other code might be using, you are free to add your own custom properties to the response object. That object lives only for the duration of this particular response so any properties you add to it will be temporal only for the duration of this response processing.

So, your second option is perfectly fine too:

response.body = body
resolve(response);

As for future proof, using your own custom object is the most future proof since it's your object. Nobody will ever be modifying it and there is no chance of a name collision with that first option.

As for adding properties to the response object there is no agreed upon convention for how to add custom properties to the response object that will never interfere with the future design and evolution of the object. You are probably safe if you add your own custom prefix to the property name such as response._my_body if you really want to go that way an increase your odds of being safe. You could even use a locally generated ES6 Symbol as the property name and be 100% sure of no collision though that does make the code a little more ugly.

Personally, I'd just resolve with my own object or make up my own custom property name prefix.

Comments