req-wants

An http request decorator for simplified content negotiation.

npm install req-wants
10 downloads in the last month

req-wants

NPM

An http request decorator for simplified content negotiation.

build status Dependency Status

I have been working on a project/ blog post that explains how not to use large frameworks when developing node.js http servers. Having tight control in your routes around content negotiation is one of the main reasons I prefer to avoid frameworks in general.

This module makes it easy to see what is happening in your code at the point you decide how you are going to respond and what content-type you are going to respond with.

EXAMPLE

var http = require('http')
  , wants = require('req-wants')

http.createServer(function(req, res){

  req.wants = wants(req, res)

  if (req.wants('json')) {
    res.writeHead(200, { 'content-type': 'application/json' })
    res.write(JSON.stringify({ foo: 'bar' }))
    return res.end()
  }

  // Assuming you are using beardo or Templar
  if (req.wants('html')) return res.template('foo')

  // don't want to support anything else.
  res.statusCode = 415
  res.end()
}

}).listen(1337)

I think it's important to note that this decorator has seen several incarnations over several production projects and most of the code was initially borrowed from node-restify's req.accepts method. I think it could be a lot better though, maybe you could help out?

DEVELOPMENT

You can run the tests through standard npm commands.

$ npm install   # install dependencies
$ npm test      # run the tests

CONTRIBUTING

Want to help? Send a pull request, I'll give you commit access and we can make this better.

If a PR is too much any feedback is always welcome, I prefer GH issues but a tweet or IRC chat is fine as well :)

LICENSE (MIT)

Copyright (c) Jason Campbell ("Author")

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

npm loves you