How can I extend node.js request object and add custom methods and properties to it? I need to be able to access this
from node's request though since I'll need the url and such.
The request object passed to the http.createServer
callback is an http.IncomingMessage
object. To augment the request object, you can add methods to http.IncomingMessage.prototype
.
var http = require('http');
http.IncomingMessage.prototype.userAgent = function () {
return this.headers['user-agent'];
}
To add an accessor property:
Object.defineProperty(http.IncomingMessage.prototype, 'userAgent', {
get: function () {
return this.headers['user-agent'];
}
}
If your existing object has its methods defined in the constructor body, you can use delegation:
function AugmentedRequest() {
this.userAgent = function () {}
}
AugmentedRequest.call(request); //request now has a userAgent method
Another method, that doesn't involve augmenting the request
object is to use composition.
var extendedRequest = {
get userAgent() {
this.request.headers['user-agent'];
}
}
createServerCallback(function (req, res) {
var request = Object.create(extendedRequest);
request.request = req;
});
This technique is heavily employed in koa to wrap Node objects.
You can pass your own classes into the createServer function.
const {createServer, IncomingMessage, ServerResponse} = require('http')
// extend the default classes
class CustomReponse extends ServerResponse {
json(data) {
this.setHeader("Content-Type", "application/json");
this.end(JSON.stringify(data))
}
status(code) {
this.statusCode = code
return this
}
}
class CustomRequest extends IncomingMessage {
// extend me too
}
// and use as server options
const serverOptions = {
IncomingMessage: CustomRequest,
ServerResponse: CustomReponse,
}
createServer(serverOptions, (req, res) => {
// example usage
res.status(404).json({
error: 'not found',
message: 'the requested resource does not exists'
})
}).listen(3000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With