UNPKG

@sap/xsodata

Version:

Expose data from a HANA database as OData V2 service with help of .xsodata files.

128 lines (103 loc) 3.48 kB
"use strict"; var _ = require('lodash'); var utils = require('./../utils/utils'); var bodyParser = require('body-parser'); /** * Load the limit information from the xsodata file * @param sqlContext * @param {string} name Name of the limit setting (e.g. 'max_records') * @returns {*} */ function getLimit(context, name) { if (!context) {return null;} const model = context.gModel; if (model && model._settings && model._settings.limits) { const limit = model._settings.limits[name]; return limit; } return null; } module.exports.createRequest = function (originalRequest, context) { var request = { headers: {} }; if (originalRequest) { request = { httpVersion: originalRequest.httpVersion, headers: utils.clone(originalRequest.headers), method: originalRequest.method, url: originalRequest.url, urlData: createUrlData(originalRequest), baseUrl: context.uriPrefix || originalRequest.baseUrl || '' }; } //Express JS handling if (originalRequest.body) { request.body = originalRequest.body; } request.getBodyAsString = function (cb) { if (request.body) { if (request.body instanceof Buffer) { return cb(null,request.body.toString('utf8')); } else { return cb(null,request.body); } } else if (originalRequest.body) { return cb(null,originalRequest.body); } else { let maxBodySize = getLimit(context, "max_body_size"); if (!maxBodySize) { maxBodySize = context.handlerConfiguration.maxBodySize; } var parser = bodyParser.raw({ type: '*/*', limit: maxBodySize }); parser(originalRequest, null, function next(err) { //if (err) { // throw new BadRequest('Error while parsing http content', null, err); //} var body = originalRequest.body; return cb(err, body.toString('utf8')); }); } }; return request; }; module.exports.createRequestFromAppHttp = function (appHttp, options) { var request; var appData = appHttp.rawData; var s = appData.url.split(' '); if (s.length !== 3) { throw new Error('Invalid URI format inside batch request.'); } var method = s[0]; var uri = s[1]; var version = s[2]; var body = appData.payload.join('\r\n'); if (uri.substr(0, 1) !== '/') { uri = '/' + uri; } request = { httpVersion: version, headers: utils.clone(appData.headers), method: method, url: uri, body: body }; request.urlData = createUrlData(request); if (options) { _.assign(request, options); } request.getBodyAsString = function (cb) { return cb(null, request.body); }; return request; }; function createUrlData(request) { var protocol = request.connection && request.connection.encrypted ? 'https' : 'http'; return { host: request.headers['x-forwarded-host'] || request.headers.host, proto: request.headers['x-forwarded-proto'] || request.protocol || protocol, path: request.headers['x-forwarded-path'] || request.url, forwarded: !!request.headers['x-forwarded-path'], baseUrl: request.baseUrl }; }