-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
97 lines (79 loc) · 2.54 KB
/
app.js
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
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict';
// Loading the express library
var express = require('express');
var app = express();
var async = require('async');
var service = require('./routes/index');
var logError = require('./routes/logerror');
var errorHandler = require('./routes/errorhandler');
var configuration = require('./middleware/configuration');
var auth = require('./middleware/auth');
var Nonce = require('./middleware/Nonce');
var loggingBefore = require('./middleware/logging_before');
var etagBefore = require('./middleware/etag_before');
var loggingAfter = require('./middleware/logging_after');
var etagAfter = require('./middleware/etag_after');
/// Function to sort the order of the middleware to be executed
var sortConfig = function(confirguration){
var sortable = [];
for (var middleware in confirguration)
// To make middlewares configurable
if (confirguration[middleware]['enable'] == true){
sortable.push([middleware, confirguration[middleware]['priority']]);
}
sortable.sort(function(a, b) {return b[1] - a[1]});
return sortable;
}
function configurableMiddleWare(req, res, next) {
var config = req.configuration;
var operations = [];
var middleware;
var sortedConfig = sortConfig(config);
// push each middleware you want to run
sortedConfig.forEach(function(fn) {
switch(fn[0]){
case 'auth':
middleware = auth;
break;
case 'Nonce':
middleware = Nonce.checkNonce;
break;
case 'loggingBefore':
middleware = loggingBefore;
break;
case 'etagBefore':
middleware = etagBefore;
break;
case 'service':
middleware = service;
break;
case 'loggingAfter':
middleware = loggingAfter.log;
break;
case 'etagAfter':
middleware = etagAfter;
break;
}
// console.log(fn[0]);
// console.log(middleware);
// Push the middleware into the array and pass the variable to it
operations.push(middleware.bind(middleware, req, res)); // could use fn.bind(null, req, res) to pass in vars
});
console.log('middleware list sorted');
// now actually invoke the middleware in series
async.series(operations, function(err) {
if(err) {
console.log('Something blew up!!!!!!');
loggingAfter.log(req, res);
}
console.log('middleware get executed');
// no errors so pass control back to expresss
next();
});
}
app.use('/service',configuration);
app.use('/service', configurableMiddleWare);
app.use(logError);
app.use(errorHandler);
// export the module so that it could be called elsewhere
module.exports = app;