forked from linnovate/mean
-
Notifications
You must be signed in to change notification settings - Fork 0
/
express.js
executable file
·206 lines (164 loc) · 6.14 KB
/
express.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
'use strict';
/**
* Module dependencies.
*/
var express = require('express'),
favicon = require('static-favicon'),
morgan = require('morgan'),
compression = require('compression'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
errorHandler = require('errorhandler'),
mean = require('meanio'),
consolidate = require('consolidate'),
mongoStore = require('mean-connect-mongo')(session),
flash = require('connect-flash'),
helpers = require('view-helpers'),
config = require('./config'),
expressValidator = require('express-validator'),
appPath = process.cwd(),
util = require('./util'),
assetmanager = require('assetmanager'),
fs = require('fs'),
Grid = require('gridfs-stream');
module.exports = function(app, passport, db) {
var gfs = new Grid(db.connections[0].db, db.mongo);
app.set('showStackError', true);
// Prettify HTML
app.locals.pretty = true;
// cache=memory or swig dies in NODE_ENV=production
app.locals.cache = 'memory';
// Should be placed before express.static
// To ensure that all assets and data are compressed (utilize bandwidth)
app.use(compression({
// Levels are specified in a range of 0 to 9, where-as 0 is
// no compression and 9 is best compression, but slowest
level: 9
}));
// Only use logger for development environment
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// assign the template engine to .html files
app.engine('html', consolidate[config.templateEngine]);
// set .html as the default extension
app.set('view engine', 'html');
// Set views path, template engine and default layout
app.set('views', config.root + '/server/views');
// Enable jsonp
app.enable('jsonp callback');
// The cookieParser should be above session
app.use(cookieParser());
// Request body parsing middleware should be above methodOverride
app.use(expressValidator());
app.use(bodyParser());
app.use(methodOverride());
app.use(cookieParser());
// Import your asset file
var assets = require('./assets.json');
assetmanager.init({
js: assets.js,
css: assets.css,
debug: (process.env.NODE_ENV !== 'production'),
webroot: 'public/public'
});
// Add assets to local variables
app.use(function(req, res, next) {
res.locals.assets = assetmanager.assets;
next();
});
// Express/Mongo session storage
app.use(session({
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
// Dynamic helpers
app.use(helpers(config.app.name));
// Use passport session
app.use(passport.initialize());
app.use(passport.session());
//mean middleware from modules before routes
app.use(mean.chainware.before);
// Connect flash for flash messages
app.use(flash());
// Setting the fav icon and static folder
app.use(favicon());
app.get('/modules/aggregated.js', function(req, res) {
res.setHeader('content-type', 'text/javascript');
res.send(mean.aggregated.js);
});
function themeHandler(req, res) {
res.setHeader('content-type', 'text/css');
gfs.files.findOne({
filename: 'theme.css'
}, function(err, file) {
if (!file) {
fs.createReadStream(process.cwd() + '/public/system/lib/bootstrap/dist/css/bootstrap.css').pipe(res);
} else {
// streaming to gridfs
var readstream = gfs.createReadStream({
filename: 'theme.css'
});
//error handling, e.g. file does not exist
readstream.on('error', function(err) {
console.log('An error occurred!', err.message);
throw err;
});
readstream.pipe(res);
}
});
}
// We override this file to allow us to swap themes
// We keep the same public path so we can make use of the bootstrap assets
app.get('/public/system/lib/bootstrap/dist/css/bootstrap.css', themeHandler);
app.get('/modules/aggregated.css', function(req, res) {
res.setHeader('content-type', 'text/css');
res.send(mean.aggregated.css);
});
app.use('/public', express.static(config.root + '/public'));
mean.events.on('modulesFound', function() {
for (var name in mean.modules) {
app.use('/' + name, express.static(config.root + '/' + mean.modules[name].source + '/' + name + '/public'));
}
function bootstrapRoutes() {
// Skip the app/routes/middlewares directory as it is meant to be
// used and shared by routes as further middlewares and is not a
// route by itself
util.walk(appPath + '/server/routes', 'middlewares', function(path) {
require(path)(app, passport);
});
}
bootstrapRoutes();
//mean middlware from modules after routes
app.use(mean.chainware.after);
// Assume "not found" in the error msgs is a 404. this is somewhat
// silly, but valid, you can do whatever you like, set properties,
// use instanceof etc.
app.use(function(err, req, res, next) {
// Treat as 404
if (~err.message.indexOf('not found')) return next();
// Log it
console.error(err.stack);
// Error page
res.status(500).render('500', {
error: err.stack
});
});
// Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not found'
});
});
// Error handler - has to be last
if (process.env.NODE_ENV === 'development') {
app.use(errorHandler());
}
});
};