-
Notifications
You must be signed in to change notification settings - Fork 953
/
app.js
267 lines (211 loc) · 6.42 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
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
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http');
var _ = require('underscore');
var utils = require('./utils');
var mongodb = require('mongodb');
//var cons = require('consolidate');
var swig = require('swig');
var swigFilters = require('./filters');
var app = express();
//Set up swig
swig.init({
root: __dirname + '/views',
allowErrors: false,
filters: swigFilters
});
/*
* Monkey-patching swig until swig supports express
*/
swig.__express = function(path, options, fn) {
options = options || {};
try {
options.filename = path;
var tmpl = swig.compileFile(_.last(path.split('/')));
fn(null, tmpl.render(options));
} catch (err) {
fn(err);
}
};
//App configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.engine('.html', swig.__express);
app.set('view engine', 'html');
app.set('view options', {layout: false});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
//Set up database stuff
var config = require('./config');
var host = config.mongodb.server || 'localhost';
var port = config.mongodb.port || mongodb.Connection.DEFAULT_PORT;
var dbOptions = {
auto_reconnect: config.mongodb.autoReconnect,
poolSize: config.mongodb.poolSize
};
var db = new mongodb.Db('local', new mongodb.Server(host, port, dbOptions));
var connections = {};
var databases = [];
var collections = {};
var adminDb;
var mainConn; //main db connection
//Update the collections list
var updateCollections = function(db, dbName, callback) {
db.collectionNames(function (err, result) {
var names = [];
for (var r in result) {
var coll = utils.parseCollectionName(result[r].name);
names.push(coll.name);
}
collections[dbName] = names.sort();
if (callback) {
callback(err);
}
});
};
//Update database list
var updateDatabases = function(admin) {
admin.listDatabases(function(err, dbs) {
if (err) {
//TODO: handle error
console.error(err);
}
for (var key in dbs.databases) {
var dbName = dbs.databases[key]['name'];
//'local' is special database, ignore it
if (dbName == 'local') {
continue;
}
if (config.mongodb.whitelist.length != 0) {
if (!_.include(config.mongodb.whitelist, dbName)) {
continue;
}
}
if (config.mongodb.blacklist.length != 0) {
if (_.include(config.mongodb.blacklist, dbName)) {
continue;
}
}
connections[dbName] = mainConn.db(dbName);
databases.push(dbName);
updateCollections(connections[dbName], dbName);
}
//Sort database names
databases = databases.sort();
});
};
//Connect to mongodb database
db.open(function(err, db) {
if (!err) {
console.log('Database connected!');
mainConn = db;
//get admin instance
db.admin(function(err, a) {
adminDb = a;
if (config.mongodb.username.length == 0) {
console.log('Admin DB connected');
updateDatabases(adminDb);
} else {
//auth details were supplied, authenticate admin account with them
adminDb.authenticate(config.mongodb.username, config.mongodb.password, function(err, result) {
if (err) {
//TODO: handle error
console.error(err);
}
console.log('Admin DB connected');
updateDatabases(adminDb);
});
}
});
} else {
throw err;
}
});
//View helper, sets local variables used in templates
app.locals.use(function(req, res) {
res.locals.baseHref = config.site.baseUrl;
res.locals.databases = databases;
res.locals.collections = collections;
});
//route param pre-conditions
app.param('database', function(req, res, next, id) {
//Make sure database exists
if (!_.include(databases, id)) {
//TODO: handle error
return next('Error! Database not found!');
}
req.dbName = id;
res.locals.dbName = id;
if (connections[id] !== undefined) {
req.db = connections[id];
} else {
connections[id] = mainConn.db(id);
req.db = connections[id];
}
next();
});
//:collection param MUST be preceded by a :database param
app.param('collection', function(req, res, next, id) {
//Make sure collection exists
if (!_.include(collections[req.dbName], id)) {
//TODO: handle error
return next('Error!');
}
req.collectionName = id;
res.locals.collectionName = id;
connections[req.dbName].collection(id, function(err, coll) {
if (err) {
//TODO: handle error
return next('Error! Collection not found!');
}
req.collection = coll;
next();
});
});
//:document param MUST be preceded by a :collection param
app.param('document', function(req, res, next, id) {
//Convert id string to mongodb object ID
var id = new mongodb.ObjectID.createFromHexString(id);
req.collection.findOne({_id: id}, function(err, doc) {
if (err) {
//TODO: handle error
return next('Error! Document not found!');
}
req.document = doc;
res.locals.document = doc;
next();
});
});
//mongodb middleware
var middleware = function(req, res, next) {
req.adminDb = adminDb;
req.databases = databases; //List of database names
req.collections = collections; //List of collection names in all databases
//Allow page handlers to request an update for collection list
req.updateCollections = updateCollections;
next();
};
//Routes
app.get('/', middleware, routes.index);
app.get('/db/:database/:collection/:document', middleware, routes.viewDocument);
app.put('/db/:database/:collection/:document', middleware, routes.updateDocument);
app.del('/db/:database/:collection/:document', middleware, routes.deleteDocument);
app.post('/db/:database/:collection', middleware, routes.addDocument);
app.get('/db/:database/:collection', middleware, routes.viewCollection);
app.put('/db/:database/:collection', middleware, routes.renameCollection);
app.del('/db/:database/:collection', middleware, routes.deleteCollection);
app.post('/db/:database', middleware, routes.addCollection);
app.get('/db/:database', middleware, routes.viewDatabase);
app.listen(config.site.port || 80);
console.log("Mongo Express server listening on port " + (config.site.port || 80));