index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*!
  2. * negotiator
  3. * Copyright(c) 2012 Federico Romero
  4. * Copyright(c) 2012-2014 Isaac Z. Schlueter
  5. * Copyright(c) 2015 Douglas Christopher Wilson
  6. * MIT Licensed
  7. */
  8. 'use strict';
  9. var preferredCharsets = require('./lib/charset')
  10. var preferredEncodings = require('./lib/encoding')
  11. var preferredLanguages = require('./lib/language')
  12. var preferredMediaTypes = require('./lib/mediaType')
  13. /**
  14. * Module exports.
  15. * @public
  16. */
  17. module.exports = Negotiator;
  18. module.exports.Negotiator = Negotiator;
  19. /**
  20. * Create a Negotiator instance from a request.
  21. * @param {object} request
  22. * @public
  23. */
  24. function Negotiator(request) {
  25. if (!(this instanceof Negotiator)) {
  26. return new Negotiator(request);
  27. }
  28. this.request = request;
  29. }
  30. Negotiator.prototype.charset = function charset(available) {
  31. var set = this.charsets(available);
  32. return set && set[0];
  33. };
  34. Negotiator.prototype.charsets = function charsets(available) {
  35. return preferredCharsets(this.request.headers['accept-charset'], available);
  36. };
  37. Negotiator.prototype.encoding = function encoding(available) {
  38. var set = this.encodings(available);
  39. return set && set[0];
  40. };
  41. Negotiator.prototype.encodings = function encodings(available) {
  42. return preferredEncodings(this.request.headers['accept-encoding'], available);
  43. };
  44. Negotiator.prototype.language = function language(available) {
  45. var set = this.languages(available);
  46. return set && set[0];
  47. };
  48. Negotiator.prototype.languages = function languages(available) {
  49. return preferredLanguages(this.request.headers['accept-language'], available);
  50. };
  51. Negotiator.prototype.mediaType = function mediaType(available) {
  52. var set = this.mediaTypes(available);
  53. return set && set[0];
  54. };
  55. Negotiator.prototype.mediaTypes = function mediaTypes(available) {
  56. return preferredMediaTypes(this.request.headers.accept, available);
  57. };
  58. // Backwards compatibility
  59. Negotiator.prototype.preferredCharset = Negotiator.prototype.charset;
  60. Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets;
  61. Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding;
  62. Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings;
  63. Negotiator.prototype.preferredLanguage = Negotiator.prototype.language;
  64. Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages;
  65. Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType;
  66. Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;