3 * Copyright(c) 2012 Federico Romero
4 * Copyright(c) 2012-2014 Isaac Z. Schlueter
5 * Copyright(c) 2015 Douglas Christopher Wilson
12 * Cached loaded submodules.
16 var modules = Object.create(null);
23 module.exports = Negotiator;
24 module.exports.Negotiator = Negotiator;
27 * Create a Negotiator instance from a request.
28 * @param {object} request
32 function Negotiator(request) {
33 if (!(this instanceof Negotiator)) {
34 return new Negotiator(request);
37 this.request = request;
40 Negotiator.prototype.charset = function charset(available) {
41 var set = this.charsets(available);
45 Negotiator.prototype.charsets = function charsets(available) {
46 var preferredCharsets = loadModule('charset').preferredCharsets;
47 return preferredCharsets(this.request.headers['accept-charset'], available);
50 Negotiator.prototype.encoding = function encoding(available) {
51 var set = this.encodings(available);
55 Negotiator.prototype.encodings = function encodings(available) {
56 var preferredEncodings = loadModule('encoding').preferredEncodings;
57 return preferredEncodings(this.request.headers['accept-encoding'], available);
60 Negotiator.prototype.language = function language(available) {
61 var set = this.languages(available);
65 Negotiator.prototype.languages = function languages(available) {
66 var preferredLanguages = loadModule('language').preferredLanguages;
67 return preferredLanguages(this.request.headers['accept-language'], available);
70 Negotiator.prototype.mediaType = function mediaType(available) {
71 var set = this.mediaTypes(available);
75 Negotiator.prototype.mediaTypes = function mediaTypes(available) {
76 var preferredMediaTypes = loadModule('mediaType').preferredMediaTypes;
77 return preferredMediaTypes(this.request.headers.accept, available);
80 // Backwards compatibility
81 Negotiator.prototype.preferredCharset = Negotiator.prototype.charset;
82 Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets;
83 Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding;
84 Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings;
85 Negotiator.prototype.preferredLanguage = Negotiator.prototype.language;
86 Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages;
87 Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType;
88 Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
91 * Load the given module.
95 function loadModule(moduleName) {
96 var module = modules[moduleName];
98 if (module !== undefined) {
102 // This uses a switch for static require analysis
103 switch (moduleName) {
105 module = require('./lib/charset');
108 module = require('./lib/encoding');
111 module = require('./lib/language');
114 module = require('./lib/mediaType');
117 throw new Error('Cannot find module \'' + moduleName + '\'');
120 // Store to prevent invoking require()
121 modules[moduleName] = module;