@sap/cds
Version:
SAP Cloud Application Programming Model - CDS for Node.js
50 lines (46 loc) • 1.6 kB
JavaScript
const cds = require('../../../lib')
const odata = require('../index')
const bodyParser4 = require('../../http/body-parser')
const { isStream } = require('../utils')
/**
* @param {import('../ODataAdapter')} adapter
* the adapter instance in which this middleware is used
*/
module.exports = adapter => {
const { service } = adapter
const bodyParser = bodyParser4(adapter)
/**
* @type {import('express').RequestHandler}
*/
return function parse_odata_url(req, res, next) {
if (req.path !== '/$batch')
req._query ??= odata.parse(req.url, {
service,
baseUrl: req.baseUrl,
strict: true,
protocol: 'odata'
})
switch (req.method) {
case 'POST':
if (req.get('content-type')?.includes('multipart/mixed')) return next()
if (req.get('content-type')?.includes('application/json')) break
if ((req.get('content-length') || 0) == 0)
break // works for '0', 0, and undefined
else throw cds.error(415)
case 'PUT':
if (isStream(req._query)) {
req.body = { value: req }
return next()
}
// falls through
case 'PATCH':
if (req._query?.SELECT?.from.ref?.slice(-1)[0]?.operation)
throw cds.error(405, `Method ${req.method} not allowed for calling custom actions`)
if (req.get('content-type')?.includes('application/json'))
if (req.get('content-length') == 0) throw cds.error(400, 'Expected non-empty body')
else break
else throw cds.error(415)
}
return bodyParser(req, res, next)
}
}