UNPKG

@chubbyts/chubbyts-negotiation

Version:
33 lines (32 loc) 1.25 kB
import { resolveHeaderToMap } from './negotiation.js'; const compareMediaTypeWithSuffix = (supportedValues, mediaType, attributes) => { const mediaTypeParts = mediaType.match(/([^/]+)\/([^+]+)\+(.+)/); if (null === mediaTypeParts) { return undefined; } const mediaTypeFromParts = mediaTypeParts[1] + '/' + mediaTypeParts[3]; if (-1 !== supportedValues.indexOf(mediaTypeFromParts)) { return { value: mediaTypeFromParts, attributes }; } }; const compareMediaTypes = (supportedValues, headerToMap) => { const entries = Array.from(headerToMap.entries()); if (entries.length !== 1) { return undefined; } const [mediaType, attributes] = entries[0]; const { q: _, ...otherAttriutes } = attributes; if (-1 !== supportedValues.indexOf(mediaType)) { return { value: mediaType, attributes: otherAttriutes }; } return compareMediaTypeWithSuffix(supportedValues, mediaType, otherAttriutes); }; export const createContentTypeNegotiator = (supportedValues) => { return { negotiate: (header) => { const headerToMap = resolveHeaderToMap(header); return compareMediaTypes(supportedValues, headerToMap); }, supportedValues, }; };