@chubbyts/chubbyts-api
Version:
[](https://github.com/chubbyts/chubbyts-api/actions?query=workflow%3ACI) [ • 1.11 kB
JavaScript
import { createUnsupportedMediaType } from '@chubbyts/chubbyts-http-error/dist/http-error';
export const createContentTypeNegotiationMiddleware = (contentTypeNegotiator) => {
return async (request, handler) => {
if (typeof request.headers['content-type'] === 'undefined') {
const supportedValues = contentTypeNegotiator.supportedValues;
throw createUnsupportedMediaType({
detail: `Missing content-type: "${supportedValues.join('", "')}"`,
supportedValues,
});
}
const negotiatedValue = contentTypeNegotiator.negotiate(request.headers['content-type'].join(','));
if (!negotiatedValue) {
const supportedValues = contentTypeNegotiator.supportedValues;
throw createUnsupportedMediaType({
detail: `Allowed content-types: "${supportedValues.join('", "')}"`,
supportedValues,
});
}
return handler({
...request,
attributes: { ...request.attributes, contentType: negotiatedValue.value },
});
};
};