UNPKG

@chubbyts/chubbyts-negotiation

Version:
39 lines (38 loc) 1.38 kB
import { resolveHeaderToMap } from './negotiation.js'; const compareLanguage = (locale, supportedValues, attributes) => { const localeParts = locale.match(/([^-]+)-([^-]+)$/); if (null === localeParts) { return undefined; } const language = localeParts[1]; if (supportedValues.some((supportedLocale) => supportedLocale === language)) { return { value: language, attributes }; } return undefined; }; const compareAcceptLanguages = (supportedValues, headerToMap) => { for (const [locale, attributes] of headerToMap.entries()) { if (-1 !== supportedValues.indexOf(locale)) { return { value: locale, attributes }; } } for (const [locale, attributes] of headerToMap.entries()) { const negotiatedValue = compareLanguage(locale, supportedValues, attributes); if (undefined !== negotiatedValue) { return negotiatedValue; } } if (headerToMap.has('*')) { return { value: supportedValues[0], attributes: headerToMap.get('*') }; } return undefined; }; export const createAcceptLanguageNegotiator = (supportedValues) => { return { negotiate: (header) => { const headerToMap = resolveHeaderToMap(header); return compareAcceptLanguages(supportedValues, headerToMap); }, supportedValues, }; };