Name: js-handler/node_modules/restify/lib/plugins/accept.js
| 1: | // Copyright 2012 Mark Cavage, Inc. All rights reserved. |
| 2: | |
| 3: | var assert = require('assert-plus'); |
| 4: | var mime = require('mime'); |
| 5: | |
| 6: | var NotAcceptableError = require('../errors').NotAcceptableError; |
| 7: | |
| 8: | |
| 9: | /** |
| 10: | * Returns a plugin that will check the client's Accept header can be handled |
| 11: | * by this server. |
| 12: | * |
| 13: | * Note you can get the set of types allowed from a restify server by doing |
| 14: | * `server.acceptable`. |
| 15: | * |
| 16: | * @param {String} array of accept types. |
| 17: | * @return {Function} restify handler. |
| 18: | * @throws {TypeError} on bad input |
| 19: | */ |
| 20: | function acceptParser(acceptable) { |
| 21: | if (!Array.isArray(acceptable)) |
| 22: | acceptable = [acceptable]; |
| 23: | assert.arrayOfString(acceptable, 'acceptable'); |
| 24: | |
| 25: | acceptable = acceptable.filter(function (a) { |
| 26: | return (a); |
| 27: | }).map(function (a) { |
| 28: | return ((a.indexOf('/') === -1) ? mime.lookup(a) : a); |
| 29: | }).filter(function (a) { |
| 30: | return (a); |
| 31: | }); |
| 32: | |
| 33: | var e = new NotAcceptableError('Server accepts: ' + acceptable.join()); |
| 34: | |
| 35: | function parseAccept(req, res, next) { |
| 36: | if (req.accepts(acceptable)) { |
| 37: | next(); |
| 38: | return; |
| 39: | } |
| 40: | |
| 41: | res.json(e); |
| 42: | next(false); |
| 43: | } |
| 44: | |
| 45: | return (parseAccept); |
| 46: | } |
| 47: | |
| 48: | module.exports = acceptParser; |
