Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend nodejs request object

Tags:

node.js

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.

like image 291
sandelius Avatar asked Mar 18 '23 05:03

sandelius


2 Answers

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.

like image 75
c.P.u1 Avatar answered Apr 01 '23 01:04

c.P.u1


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)
like image 25
The Fool Avatar answered Apr 01 '23 00:04

The Fool