forked from pouchdb/express-pouchdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
462 lines (391 loc) · 12.2 KB
/
index.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
var express = require('express')
, fs = require('fs')
, pkg = require('./package.json')
, dbs = {}
, app = module.exports = express()
, Pouch = module.exports.Pouch = require('pouchdb');
// We'll need this for the _all_dbs route.
Pouch.enableAllDbs = true;
app.configure(function () {
app.use('/js', express.static(__dirname + '/fauxton/js'));
app.use('/css', express.static(__dirname + '/fauxton/css'));
app.use('/img', express.static(__dirname + '/fauxton/img'));
app.use(function (req, res, next) {
var opts = {}
, data = ''
, prop;
// Normalize query string parameters for direct passing
// into Pouch queries.
for (prop in req.query) {
try {
req.query[prop] = JSON.parse(req.query[prop]);
} catch (e) {}
}
// Custom bodyParsing because express.bodyParser() chokes
// on `malformed` requests.
req.on('data', function (chunk) { data += chunk; });
req.on('end', function () {
if (data) {
try {
req.body = JSON.parse(data);
} catch (e) {
req.body = data;
}
}
next();
});
});
});
// Root route, return welcome message
app.get('/', function (req, res, next) {
res.send(200, {
'express-pouchdb': 'Welcome!',
'version': pkg.version
});
});
app.get('/_session', function (req, res, next) {
res.send({"ok":true,"userCtx":{"name":null,"roles":["_admin"]},"info":{}});
});
app.get('/_utils', function (req, res, next) {
res.sendfile(__dirname + '/fauxton/index.html');
});
// Generate UUIDs
app.get('/_uuids', function (req, res, next) {
var count = req.query.count || 1
, uuids = [];
while (--count >= 0) { uuids.push(Pouch.uuid()); }
res.send(200, {
uuids: uuids
});
});
// List all databases.
app.get('/_all_dbs', function (req, res, next) {
Pouch.allDbs(function (err, response) {
if (err) res.send(500, Pouch.UNKNOWN_ERROR);
res.send(200, response);
});
});
// Replicate a database
app.post('/_replicate', function (req, res, next) {
var source = req.body.source
, target = req.body.target
, opts = { continuous: !!req.body.continuous };
if (req.body.filter) opts.filter = req.body.filter;
if (req.body.query_params) opts.query_params = req.body.query_params;
opts.complete = function (err, response) {
if (err) return res.send(400, err);
res.send(200, response);
};
Pouch.replicate(source, target, opts);
// if continuous pull replication return 'ok' since we cannot wait for callback
if (target in dbs && opts.continuous) {
res.send(200, { ok : true });
}
});
app.get('/_active_tasks', function (req, res, next) {
res.send(200, []);
});
// Create a database.
app.put('/:db', function (req, res, next) {
var name = encodeURIComponent(req.params.db);
if (name in dbs) {
return res.send(412, {
'error': 'file_exists',
'reason': 'The database could not be created.'
});
}
Pouch(name, function (err, db) {
if (err) return res.send(412, err);
dbs[name] = db;
var loc = req.protocol
+ '://'
+ ((req.host === '127.0.0.1') ? '' : req.subdomains.join('.') + '.')
+ req.host
+ '/' + name;
res.location(loc);
res.send(201, { ok: true });
});
});
// Delete a database
app.del('/:db', function (req, res, next) {
var name = encodeURIComponent(req.params.db);
Pouch.destroy(name, function (err, info) {
if (err) return res.send(404, err);
delete dbs[name];
res.send(200, { ok: true });
});
});
// At this point, some route middleware can take care of identifying the
// correct Pouch instance.
['/:db/*','/:db'].forEach(function (route) {
app.all(route, function (req, res, next) {
var name = encodeURIComponent(req.params.db);
if (name in dbs) {
req.db = dbs[name];
return next();
}
// Check for the data stores, and rebuild a Pouch instance if able
fs.stat(name, function (err, stats) {
if (err && err.code == 'ENOENT') {
return res.send(404, {
status: 404,
error: 'not_found',
reason: 'no_db_file'
});
}
if (stats.isDirectory()) {
Pouch(name, function (err, db) {
if (err) return res.send(412, err);
dbs[name] = db;
req.db = db;
return next();
});
}
});
});
});
// Get database information
app.get('/:db', function (req, res, next) {
req.db.info(function (err, info) {
if (err) return res.send(404, err);
res.send(200, info);
});
});
// Bulk docs operations
app.post('/:db/_bulk_docs', function (req, res, next) {
// Maybe this should be moved into the leveldb adapter itself? Not sure
// how uncommon it is for important options to come through in the body
// https://github.com/daleharvey/pouchdb/issues/435
var opts = 'new_edits' in req.body
? { new_edits: req.body.new_edits }
: null;
req.db.bulkDocs(req.body, opts, function (err, response) {
if (err) return res.send(400, err);
res.send(201, response);
});
});
// All docs operations
app.all('/:db/_all_docs', function (req, res, next) {
if (req.method !== 'GET' && req.method !== 'POST') return next();
// Check that the request body, if present, is an object.
if (!!req.body && (typeof req.body !== 'object' || Array.isArray(req.body))) {
return res.send(400, Pouch.BAD_REQUEST);
}
for (var prop in req.body) {
req.query[prop] = req.query[prop] || req.body[prop];
}
req.db.allDocs(req.query, function (err, response) {
if (err) return res.send(400, err);
res.send(200, response);
});
});
// Monitor database changes
app.get('/:db/_changes', function (req, res, next) {
// api.changes expects a property `query_params`
// This is a pretty inefficient way to do it.. Revisit?
req.query.query_params = JSON.parse(JSON.stringify(req.query));
if (req.query.filter) {
// CouchDB seems to default these to true when a filter is applied
req.query.conflicts = true;
req.query.include_docs = true;
}
var longpoll = function (err, data) {
if (err) return res.send(409, err);
if (data.results && data.results.length) {
data.last_seq = Math.max.apply(Math, data.results.map(function (r) {
return r.seq;
}));
res.send(200, data);
} else {
delete req.query.complete;
req.query.continuous = true;
req.query.onChange = function (change) {
res.send(200, change);
};
req.db.changes(req.query);
}
};
if (req.query.feed) {
req.socket.setTimeout(86400 * 1000);
req.query.complete = longpoll;
} else {
req.query.complete = function (err, response) {
if (err) return res.send(409, err);
res.send(200, response);
};
}
req.db.changes(req.query);
});
// DB Compaction
app.post('/:db/_compact', function (req, res, next) {
req.db.compact(function (err, response) {
if (err) return res.send(500, err);
res.send(200, response);
});
});
// Revs Diff
app.post('/:db/_revs_diff', function (req, res, next) {
req.db.revsDiff(req.body || {}, function (err, diffs) {
if (err) return res.send(400, err);
res.send(200, diffs);
});
});
// Temp Views
app.post('/:db/_temp_view', function (req, res, next) {
if (req.body.map) req.body.map = (new Function('return ' + req.body.map))();
req.query.conflicts = true;
req.db.query(req.body, req.query, function (err, response) {
if (err) return res.send(400, err);
res.send(200, response);
});
});
// Put a document attachment
app.put('/:db/:id/:attachment(*)', function (req, res, next) {
// Be careful not to catch normal design docs or local docs
if (req.params.id === '_design' || req.params.id === '_local') {
return next();
}
var name = req.params.id
, attachment = req.params.attachment
, rev = req.query.rev
, type = req.get('Content-Type') || 'application/octet-stream'
, body = (req.body === undefined)
? new Buffer('')
: (typeof req.body === 'string')
? new Buffer(req.body)
: new Buffer(JSON.stringify(req.body));
req.db.putAttachment(name, attachment, rev, body, type, function (err, response) {
if (err) return res.send(409, err);
res.send(200, response);
});
});
// Retrieve a document attachment
app.get('/:db/:id/:attachment(*)', function (req, res, next) {
// Be careful not to catch normal design docs or local docs
if (req.params.id === '_design' || req.params.id === '_local') {
return next();
}
var name = req.params.id
, attachment = req.params.attachment;
req.db.get(req.params.id, req.query, function (err, info) {
if (err) return res.send(404, err);
if (!info._attachments || !info._attachments[attachment]) {
return res.send(404, {status:404, error:'not_found', reason:'missing'});
};
var type = info._attachments[attachment].content_type;
req.db.getAttachment(name, attachment, function (err, response) {
if (err) return res.send(409, err);
res.set('Content-Type', type);
res.send(200, response);
});
});
});
// Delete a document attachment
app.del('/:db/:id/:attachment(*)', function (req, res, next) {
// Be careful not to catch normal design docs or local docs
if (req.params.id === '_design' || req.params.id === '_local') {
return next();
}
var name = req.params.id
, attachment = req.params.attachment
, rev = req.query.rev;
req.db.removeAttachment(name, attachment, rev, function (err, response) {
if (err) return res.send(409, err);
res.send(200, response);
});
});
// Create or update document that has an ID
app.put('/:db/:id(*)', function (req, res, next) {
req.body._id = req.body._id || req.query.id;
if (!req.body._id) {
req.body._id = (!!req.params.id && req.params.id !== 'null')
? req.params.id
: null;
}
req.db.put(req.body, req.query, function (err, response) {
if (err) return res.send(409, err);
var loc = req.protocol
+ '://'
+ ((req.host === '127.0.0.1') ? '' : req.subdomains.join('.') + '.')
+ req.host
+ '/' + req.params.db
+ '/' + req.body._id;
res.location(loc);
res.send(201, response);
});
});
app.get('/:db/_design/:id/_info', function (req, res, next) {
// Dummy data for now. We can investigate and see if pouch can do this for us.
res.send(200, {
'name': req.query.id,
'view_index': {
'signature': '0',
'language': 'javascript',
'disk_size': 0,
'data_size': 0,
'update_seq': 0,
'purge_seq': 0,
'updater_running': false,
'compact_running': false,
'waiting_commit': false,
'waiting_clients': 0
}
});
});
// Create a document
app.post('/:db', function (req, res, next) {
req.db.post(req.body, req.query, function (err, response) {
if (err) return res.send(409, err);
res.send(201, response);
});
});
// Query a document view
app.get('/:db/_design/:id/_view/:view', function (req, res, next) {
var query = req.params.id + '/' + req.params.view;
req.db.query(query, req.query, function (err, response) {
if (err) return res.send(404, err);
res.send(200, response);
});
});
// Retrieve a document
app.get('/:db/:id', function (req, res, next) {
req.db.get(req.params.id, req.query, function (err, doc) {
if (err) return res.send(404, err);
res.send(200, doc);
});
});
// Delete a document
app.del('/:db/:id', function (req, res, next) {
req.db.get(req.params.id, req.query, function (err, doc) {
if (err) return res.send(404, err);
req.db.remove(doc, function (err, response) {
if (err) return res.send(404, err);
res.send(200, response);
});
});
});
// Copy a document
app.copy('/:db/:id', function (req, res, next) {
var dest = req.get('Destination')
, rev
, match;
if (!dest) {
return res.send(400, {
'error': 'bad_request',
'reason': 'Destination header is mandatory for COPY.'
});
}
if (match = /(.+?)\?rev=(.+)/.exec(dest)) {
dest = match[1];
rev = match[2];
}
req.db.get(req.params.id, req.query, function (err, doc) {
if (err) return res.send(404, err);
doc._id = dest;
doc._rev = rev;
req.db.put(doc, function (err, response) {
if (err) return res.send(409, err);
res.send(200, doc);
});
});
});