summaryrefslogtreecommitdiffstats
path: root/lib/middleware.js
blob: ee39863c64bf90e8361766808eaaa39356ecd223 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
Copyright(c) 2017-2018 AT&T Intellectual Property. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
*/

/* Middleware modules  */

"use strict";

const utils = require('./utils');
const log = require('./logging').getLogger();

/* Assign a request ID and start time to each incoming request */
exports.assignId = function(req, res, next) {
	/* Use request ID from header if available, otherwise generate one */
	req.startTime = new Date();
	req.dcaeReqId = req.get('X-ECOMP-RequestID') ||  utils.generateId();
	next();
};


/* Error handler -- send error with JSON body */
exports.handleErrors = function(err, req, res, next) {
	const response = {
		status : err.status || 500,
		message : err.message || err.body || 'unknown error'
	};
	if (err.stack) {
		response.stack = err.stack.split("\n");
	}

	res.status(response.status).type('application/json').send(response);
	log.audit(req, response.status, JSON.stringify(response));

	if (response.status >= 500) {
		err.message = response.message + (err.stack && " " + response.stack.join(', '));
		log.error(err, req);
	}
};

/* Make sure Content-Type is correct for POST and PUT */
exports.checkType = function(type){
	return function(req, res, next) {
		const ctype = req.header('content-type');
		const method = req.method.toLowerCase();
		/* Content-Type matters only for POST and PUT */
		if (ctype === type || ['post','put'].indexOf(method) < 0) {
			next();
		}
		else {
			var err = new Error ('Content-Type must be \'' + type +'\'');
			err.status = 415;
			next (err);
		}
	};
};

/* Check that a JSON body has a set of properties */
exports.checkProps = function(props) {
	return function (req, res, next) {
		const missing = props.filter(function(p){return !utils.hasProperty(req.body,p);});
		if (missing.length > 0) {
			var err = new Error ('Request missing required properties: ' + missing.join(','));
			err.status = 400;
			next(err);
		}
		else {
			next();
		}
	};
};