UNPKG

@sap/odata-v4

Version:

OData V4.0 server library

57 lines (49 loc) 2.48 kB
'use strict'; const RepresentationKind = require('./RepresentationKind'); const RepresentationKinds = RepresentationKind.Kinds; const HttpHeader = require('../http/HttpHeader'); const HeaderNames = HttpHeader.HeaderNames; const DeserializationError = require('../errors/DeserializationError'); /** * Negotiates the request payload type for the provided request. */ class RequestContentNegotiator { /** * Negotiates the deserializer function in dependency of the request type and sets the result * to the request contract. * * @param {FormatManager} bodyParserManager The format manager holding the deserializing function * @param {OdataRequest} request The current odata request * @returns {RequestContract} Returns the contract with attached deserializer facade */ negotiate(bodyParserManager, request) { const representationKind = RepresentationKind.getRequestRepresentationKind( request.getUriInfo(), request.getMethod()); let contract = request.getContract(); contract.setRepresentationKind(representationKind); if (representationKind !== RepresentationKinds.NO_CONTENT) { try { contract.setContentTypeInfo(HttpHeader.parseContentTypeHeader( request.getHeader(HeaderNames.CONTENT_TYPE.toLowerCase()))); } catch (error) { throw new DeserializationError( 'Invalid value "' + request.getHeader(HeaderNames.CONTENT_TYPE.toLowerCase()) + '" in ' + HeaderNames.CONTENT_TYPE.toLowerCase() + ' header', error); } } if (contract.getContentTypeInfo()) { const mimeType = contract.getContentTypeInfo().getMimeType(); let formatDescriptions = bodyParserManager.getFormatDescriptions(representationKind, mimeType); // If a binary is sent and no specific deserializer is found, // use the deserializer registered for the empty-string content type. if (!formatDescriptions.length && representationKind === RepresentationKinds.BINARY) { formatDescriptions = bodyParserManager.getFormatDescriptions(representationKind, ''); } contract.setDeserializerFunction( formatDescriptions.length ? formatDescriptions[0].getSerializerFunction() : null); } return contract; } } module.exports = RequestContentNegotiator;