How to use negotiator - 8 common examples

To help you get started, we’ve selected a few negotiator examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ethanresnick / json-api / src / steps / http / negotiate-content-type.js View on Github external
return Q.Promise(function(resolve, reject) {
    let accepts = parseAccept(acceptHeader || "*/*");
    let negotiator = new Negotiator({headers: {accept: acceptHeader}});

    // Find all the Accept clauses that specifically reference json api.
    let jsonAPIAcceptsExts = accepts.filter((it) => {
      return it.type === "application" && it.subtype === "vnd.api+json";
    }).map((it) =>
      // and map them to they extensions they ask for, trimming the quotes off
      // of each extension, because the parser's too stupid to do that.
      it.params.ext ?
      it.params.ext.split(",").map((it2) => it2.replace(/^\"+|\"+$/g, "")) :
      []
    );
    // If we have an Accept clause that asks for JSON-API
    // with exactly the extensions we're using, then we're golden.
    if(jsonAPIAcceptsExts.some((it) => arrayValuesMatch(it, usedExt))) {
      let usedExtString = usedExt.length ? `; ext="${usedExt.join(",")}"` : "";
      let supportedExtString = `supported-ext="${supportedExt.join(",")}"`;
github ethanresnick / json-api / src / controllers / Documentation.js View on Github external
handle(request, frameworkReq, frameworkRes) {
    let response = new Response();
    let negotiator = new Negotiator({headers: {accept: request.accepts}});
    let contentType = negotiator.mediaType(["text/html", "application/vnd.api+json"]);

    // set content type as negotiated & vary on accept.
    response.contentType = contentType;
    response.headers.vary = "Accept";

    // process templateData (just the type infos for now) for this particular request.
    let templateData = _.cloneDeep(this.templateData, cloneCustomizer);
    templateData.resourcesMap = mapValues(templateData.resourcesMap, (typeInfo, typeName) => {
      return this.transformTypeInfo(typeName, typeInfo, request, response, frameworkReq, frameworkRes);
    });

    if(contentType.toLowerCase() === "text/html") {
      response.body = jade.renderFile(this.template, templateData);
    }
github fortunejs / fortune / lib / net / request_listener.js View on Github external
}

  else throw new Error('Arity of requestListener function is invalid.')

  const { headers, method } = request

  // Intercept CORS preflight request.
  if (settings.useCORS && method === 'OPTIONS' &&
    'origin' in headers &&
    'access-control-request-method' in headers) {
      response.writeHead(statusMap.get('success'),
        getCorsPreflightHeaders(settings))
      return response.end()
  }

  const serializerOutput = new Negotiator(request)
    .mediaType(this.serializer.ids)

  if (!serializerOutput) {
    response.writeHead(statusMap.get(errors.NotAcceptableError))
    return response.end()
  }

  // Get the media type of the request.
  // See RFC 2045: https://www.ietf.org/rfc/rfc2045.txt
  const serializerInput = (request.headers['content-type'] || '')
    .match(/[^;]*/)[0]

  // Note that this delegates all handling of options parameters
  // to the individual serializer.
  const options = { serializerInput, serializerOutput }
github glazed-elite-developers / apey-eye / apey-eye / FormatNegotiator.js View on Github external
static selectFormatter(requestProperties) {
        let formatters = Formatters.FormattersList,
            mediaTypeFormatters = {};

        if (formatters && formatters.length > 0) {
            formatters.forEach(formatter => {
                let mediaType = formatter.getMediaType();
                mediaTypeFormatters[mediaType] = formatter;
            });

            let negotiator = new Negotiator({
                headers: {
                    accept: requestProperties._format || requestProperties._mediaType
                }
            });

            let mediaTypeAccepted = negotiator.mediaType(Object.keys(mediaTypeFormatters));
            let formatterAccepted = mediaTypeFormatters[mediaTypeAccepted];

            if (mediaTypeAccepted && formatterAccepted && (formatterAccepted.prototype instanceof Formatters.BaseFormatter)) {
                return formatterAccepted;
            }
            else {
                return DefaultProperties.Formatter;
            }
        }
        else {
github adonisjs / adonis-antl / middleware / Antl.js View on Github external
_getViaQueryString (definedLocales, allowedLocales) {
    if (typeof (definedLocales) === 'string' && definedLocales.length) {
      const detectedLocale = preferredLanguages(definedLocales, allowedLocales)
      return detectedLocale instanceof Array ? detectedLocale[0] : detectedLocale
    }
    return null
  }
github Feverqwe / Mono / mono / localeMixin.js View on Github external
getLocale() {
    let availableLanguages = [];
    if (Array.isArray(navigator.languages)) {
      availableLanguages = navigator.languages;
    } else
    if (navigator.language) {
      availableLanguages = [navigator.language];
    }
    const languages = preferredLanguages(availableLanguages.join(','), Object.keys(this.localeMap));
    let locale = this.localeMap[this.defaultLocale];
    if (languages) {
      locale = Object.assign({}, locale, this.localeMap[languages[0]]);
    }
    return locale;
  }
};
github ehmicky / autoserver / src / protocols / adapters / http / content_negotiation / compress.js View on Github external
export const getCompressResponse = function({ specific: { req } }) {
  const negotiator = new Negotiator(req)
  const algos = negotiator.encodings()
  const compressResponse = findAlgo(algos)
  return compressResponse
}
github ehmicky / autoserver / src / protocols / adapters / http / content_negotiation / format.js View on Github external
const getAcceptFormat = function({ specific: { req } }) {
  const negotiator = new Negotiator(req)
  const mimes = negotiator.mediaTypes()

  if (mimes.length === 0) {
    return
  }

  const formatB = mimes
    .map(mime => eGetByMime({ mime, safe: true }))
    .find(formatA => formatA !== undefined)

  if (formatB !== undefined) {
    return formatB.name
  }

  const suggestions = getMimes({ safe: true })
  throwPb({

negotiator

HTTP content negotiation

MIT
Latest version published 3 years ago

Package Health Score

79 / 100
Full package analysis