jxson
5/21/2013 - 6:21 PM

Example req helpers for content negotiation.

Example req helpers for content negotiation.

  req.is = function(type){
    // http://www.w3.org/Protocols/rfc2616/rfc2616.txt section 7.2.1
    var ct = req.headers['content-type'] || 'application/octet-stream'
      , mime = require('mime')
      , index = ct.indexOf(';')

    if (index > -1) ct = ct.substring(0, index)

    mime.define({
      'application/x-www-form-urlencoded': [ 'form' ]
    })

    return mime.lookup(type) === ct
  }

  req.wants = function(type){
    var Negotiator = require('negotiator')
      , mime = require('mime')
      , negotiator = new Negotiator(req)
      , types = negotiator.preferredMediaTypes() || []

    return types[0] === mime.lookup(type)
  }