-
Notifications
You must be signed in to change notification settings - Fork 0
/
meadowlark.js
357 lines (320 loc) · 10.6 KB
/
meadowlark.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/**
* Created by sergey on 08.09.16.
*/
"use strict";
const express = require("express"),
http = require('http'),
app = express(),
cartValidation = require('./lib/cartValidation.js'),
credentials = require('./credentials.js'),
fs = require('fs'),
morgan = require('morgan'),
vhost = require('vhost'),
formidable = require('formidable'),
rest = require('connect-rest'),
favicon = require('serve-favicon'),
Vacation = require('./models/vacation'),
handlebars = require('express-handlebars')
.create({
defaultLayout: 'main',
helpers: {
section: function (name, options) {
if (!this._sections) this._sections = {};
this._sections[name] = options.fn(this);
return null;
}
}
});
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', process.env.PORT || 3000);
// use domains for better error handling
app.use(function(req, res, next){
// create a domain for this request
var domain = require('domain').create();
// handle errors on this domain
domain.on('error', function(err){
console.error('DOMAIN ERROR CAUGHT\n', err.stack);
try {
// failsafe shutdown in 5 seconds
setTimeout(function(){
console.error('Failsafe shutdown.');
process.exit(1);
}, 5000);
// disconnect from the cluster
var worker = require('cluster').worker;
if(worker) worker.disconnect();
// stop taking new requests
server.close();
try {
// attempt to use Express error route
next(err);
} catch(error){
// if Express error route failed, try
// plain Node response
console.error('Express error mechanism failed.\n', error.stack);
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Server error.');
}
} catch(error){
console.error('Unable to send 500 response.\n', error.stack);
}
});
// add the request and response objects to the domain
domain.add(req);
domain.add(res);
// execute the rest of the request chain in the domain
domain.run(next);
});
var MongoSessionStore = require('session-mongoose')(require('connect'));
var sessionStore = new MongoSessionStore({ url: credentials.mongo[app.get('env')].connectionString });
app.use(require('cookie-parser')(credentials.cookieSecret));
app.use(require('express-session')({
resave: false,
saveUninitialized: false,
secret: credentials.cookieSecret,
store: sessionStore,
}));
app.use(express.static(__dirname + '/public'));
app.use(require('body-parser')());
// logging
switch(app.get('env')){
case 'development':
// compact, colorful dev logging
app.use(require('morgan')('dev'));
break;
case 'production':
// module 'express-logger' supports daily log rotation
app.use(require('express-logger')({ path: __dirname + '/log/requests.log'}));
break;
}
// database configuration
var mongoose = require('mongoose');
var options = {
server: {
socketOptions: { keepAlive: 1 }
}
};
switch(app.get('env')){
case 'development':
mongoose.connect(credentials.mongo.development.connectionString, options);
break;
case 'production':
mongoose.connect(credentials.mongo.production.connectionString, options);
break;
default:
throw new Error('Unknown execution environment: ' + app.get('env'));
}
// initialize vacations
Vacation.find(function(err, vacations){
if(vacations.length) return;
new Vacation({
name: 'Hood River Day Trip',
slug: 'hood-river-day-trip',
category: 'Day Trip',
sku: 'HR199',
description: 'Spend a day sailing on the Columbia and ' +
'enjoying craft beers in Hood River!',
priceInCents: 9995,
tags: ['day trip', 'hood river', 'sailing', 'windsurfing', 'breweries'],
inSeason: true,
maximumGuests: 16,
available: true,
packagesSold: 0,
}).save();
new Vacation({
name: 'Oregon Coast Getaway',
slug: 'oregon-coast-getaway',
category: 'Weekend Getaway',
sku: 'OC39',
description: 'Enjoy the ocean air and quaint coastal towns!',
priceInCents: 269995,
tags: ['weekend getaway', 'oregon coast', 'beachcombing'],
inSeason: false,
maximumGuests: 8,
available: true,
packagesSold: 0,
}).save();
new Vacation({
name: 'Rock Climbing in Bend',
slug: 'rock-climbing-in-bend',
category: 'Adventure',
sku: 'B99',
description: 'Experience the thrill of rock climbing in the high desert.',
priceInCents: 289995,
tags: ['weekend getaway', 'bend', 'high desert', 'rock climbing', 'hiking', 'skiing'],
inSeason: true,
requiresWaiver: true,
maximumGuests: 4,
available: false,
packagesSold: 0,
notes: 'The tour guide is currently recovering from a skiing accident.',
}).save();
});
// flash message middleware
app.use(function(req, res, next){
// if there's a flash message, transfer
// it to the context, then clear it
res.locals.flash = req.session.flash;
delete req.session.flash;
next();
});
// set 'showTests' context property if the querystring contains test=1
app.use(function(req, res, next){
res.locals.showTests = app.get('env') !== 'production' &&
req.query.test === '1';
next();
});
// mocked weather data
function getWeatherData(){
return {
locations: [
{
name: 'Portland',
forecastUrl: 'http://www.wunderground.com/US/OR/Portland.html',
iconUrl: 'http://icons-ak.wxug.com/i/c/k/cloudy.gif',
weather: 'Overcast',
temp: '54.1 F (12.3 C)',
},
{
name: 'Bend',
forecastUrl: 'http://www.wunderground.com/US/OR/Bend.html',
iconUrl: 'http://icons-ak.wxug.com/i/c/k/partlycloudy.gif',
weather: 'Partly Cloudy',
temp: '55.0 F (12.8 C)',
},
{
name: 'Manzanita',
forecastUrl: 'http://www.wunderground.com/US/OR/Manzanita.html',
iconUrl: 'http://icons-ak.wxug.com/i/c/k/rain.gif',
weather: 'Light Rain',
temp: '55.0 F (12.8 C)',
},
],
};
}
// middleware to add weather data to context
app.use(function(req, res, next){
if(!res.locals.partials) res.locals.partials = {};
res.locals.partials.weatherContext = getWeatherData();
next();
});
// middleware to add weather data to context
app.use(function(req, res, next){
if(!res.locals.partials) res.locals.partials = {};
res.locals.partials.weatherContext = getWeatherData();
next();
});
// create "admin" subdomain...this should appear
// before all your other routes
var admin = express.Router();
app.use(require('vhost')('admin.*', admin));
// create admin routes; these can be defined anywhere
admin.get('/', function(req, res){
res.render('admin/home');
});
admin.get('/users', function(req, res){
res.render('admin/users');
});
// add routes
require('./routes.js')(app);
// api
var Attraction = require('./models/attraction.js');
rest.get('/attractions', function(req, content, cb){
Attraction.find({ approved: true }, function(err, attractions){
if(err) return cb({ error: 'Internal error.' });
cb(null, attractions.map(function(a){
return {
name: a.name,
description: a.description,
location: a.location,
};
}));
});
});
rest.post('/attraction', function(req, content, cb){
var a = new Attraction({
name: req.body.name,
description: req.body.description,
location: { lat: req.body.lat, lng: req.body.lng },
history: {
event: 'created',
email: req.body.email,
date: new Date(),
},
approved: false,
});
a.save(function(err, a){
if(err) return cb({ error: 'Unable to add attraction.' });
cb(null, { id: a._id });
});
});
rest.get('/attraction/:id', function(req, content, cb){
Attraction.findById(req.params.id, function(err, a){
if(err) return cb({ error: 'Unable to retrieve attraction.' });
cb(null, {
name: a.name,
description: a.description,
location: a.location,
});
});
});
var apiOptions = {
context: '/',
domain: require('domain').create(),
};
apiOptions.domain.on('error', function(err){
console.log('API domain error.\n', err.stack);
setTimeout(function(){
console.log('Server shutting down after API domain error.');
process.exit(1);
}, 5000);
server.close();
var worker = require('cluster').worker;
if(worker) worker.disconnect();
});
app.use(vhost('react.*', rest.rester(apiOptions)));
// add support for auto views
var autoViews = {};
app.use(function(req,res,next){
var path = req.path.toLowerCase();
// check cache; if it's there, render the view
if(autoViews[path]) return res.render(autoViews[path]);
// if it's not in the cache, see if there's
// a .handlebars file that matches
if(fs.existsSync(__dirname + '/views' + path + '.handlebars')){
autoViews[path] = path.replace(/^\//, '');
return res.render(autoViews[path]);
}
// no view found; pass on to 404 handler
next();
});
/*var rest = Rest.create( apiOptions );
app.use(rest.processRequest());*/
// 404 catch-all handler (middleware)
app.use(function(req, res){
res.status(404);
res.render('404');
});
// 500 error handler (middleware)
app.use(function(err, req, res){
console.error(err.stack);
res.status(500);
res.render('500');
});
var server;
function startServer() {
server = http.createServer(app).listen(app.get('port'), function(){
console.log( 'Express started in ' + app.get('env') +
' mode on http://localhost:' + app.get('port') +
'; press Ctrl-C to terminate.' );
});
}
if(require.main === module){
// application run directly; start app server
startServer();
} else {
// application imported as a module via "require": export function to create server
module.exports = startServer;
}