Reputation: 822
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.
Upvotes: 5
Views: 3833
Reputation: 20547
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)
Upvotes: 3
Reputation: 17094
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.
Upvotes: 7