forked from pouchdb/pouchdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
379 lines (356 loc) · 9.76 KB
/
utils.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
/* global PouchDB */
/* jshint -W079 */
'use strict';
var testUtils = {};
function uniq(list) {
var map = {};
list.forEach(function (item) {
map[item] = true;
});
return Object.keys(map);
}
testUtils.params = function () {
if (typeof module !== 'undefined' && module.exports) {
return process.env;
}
var paramStr = document.location.search.slice(1);
return paramStr.split('&').reduce(function (acc, val) {
if (!val) {
return acc;
}
var tmp = val.split('=');
acc[tmp[0]] = tmp[1] || true;
return acc;
}, {});
};
testUtils.couchHost = function () {
if (typeof module !== 'undefined' && module.exports) {
return process.env.COUCH_HOST || 'http://localhost:5984';
} else if (window && window.COUCH_HOST) {
return window.COUCH_HOST;
} else if (window && window.cordova) {
// magic route to localhost on android emulator
return 'http://10.0.2.2:2020';
}
// In the browser we default to the CORS server, in future will change
return 'http://localhost:2020';
};
testUtils.makeBlob = function (data, type) {
if (typeof module !== 'undefined' && module.exports) {
return new Buffer(data);
} else {
return PouchDB.utils.createBlob([data], { type: type });
}
};
testUtils.readBlob = function (blob, callback) {
if (typeof module !== 'undefined' && module.exports) {
callback(blob.toString());
} else {
var reader = new FileReader();
reader.onloadend = function (e) {
var binary = "";
var bytes = new Uint8Array(this.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
callback(binary);
};
reader.readAsArrayBuffer(blob);
}
};
testUtils.base64Blob = function (blob, callback) {
if (typeof module !== 'undefined' && module.exports) {
callback(blob.toString('base64'));
} else {
var reader = new FileReader();
reader.onloadend = function (e) {
var base64 = this.result.replace(/data:.*;base64,/, '');
callback(base64);
};
reader.readAsDataURL(blob);
}
};
// Prefix http adapter database names with their host and
// node adapter ones with a db location
testUtils.adapterUrl = function (adapter, name) {
if (adapter === 'http') {
return testUtils.couchHost() + '/' + name;
}
return name;
};
// Delete specified databases
testUtils.cleanup = function (dbs, done) {
dbs = uniq(dbs);
var deleted = 0;
var num = dbs.length;
var errors = [];
function dbDeleted(err, res) {
// 400 is for an unexpected return from CouchDB, filed
// https://issues.apache.org/jira/browse/COUCHDB-2205
if (err && (err.status !== 404 && err.status !== 400)) {
errors.push(err);
}
if (++deleted === num) {
if (errors.length > 0) {
// TODO: report all the errors
done(errors[0]);
} else {
done();
}
}
}
dbs.forEach(function (db) {
PouchDB.destroy(db, dbDeleted);
});
};
// Put doc after prevRev (so that doc is a child of prevDoc
// in rev_tree). Doc must have _rev. If prevRev is not specified
// just insert doc with correct _rev (new_edits=false!)
testUtils.putAfter = function (db, doc, prevRev, callback) {
var newDoc = PouchDB.extend({}, doc);
if (!prevRev) {
db.put(newDoc, { new_edits: false }, callback);
return;
}
newDoc._revisions = {
start: +newDoc._rev.split('-')[0],
ids: [
newDoc._rev.split('-')[1],
prevRev.split('-')[1]
]
};
db.put(newDoc, { new_edits: false }, callback);
};
// docs will be inserted one after another
// starting from root
testUtils.putBranch = function (db, docs, callback) {
function insert(i) {
var doc = docs[i];
var prev = i > 0 ? docs[i - 1]._rev : null;
function next() {
if (i < docs.length - 1) {
insert(i + 1);
} else {
callback();
}
}
db.get(doc._id, { rev: doc._rev }, function (err, ok) {
if (err) {
testUtils.putAfter(db, docs[i], prev, function (err, doc) {
next();
});
} else {
next();
}
});
}
insert(0);
};
testUtils.putTree = function (db, tree, callback) {
function insert(i) {
var branch = tree[i];
testUtils.putBranch(db, branch, function () {
if (i < tree.length - 1) {
insert(i + 1);
} else {
callback();
}
});
}
insert(0);
};
testUtils.writeDocs = function (db, docs, callback, res) {
if (!res) {
res = [];
}
if (!docs.length) {
return callback(null, res);
}
var doc = docs.shift();
db.put(doc, function (err, info) {
res.push(info);
testUtils.writeDocs(db, docs, callback, res);
});
};
// Borrowed from: http://stackoverflow.com/a/840849
testUtils.eliminateDuplicates = function (arr) {
var i, element, len = arr.length, out = [], obj = {};
for (i = 0; i < len; i++) {
obj[arr[i]] = 0;
}
for (element in obj) {
if (obj.hasOwnProperty(element)) {
out.push(element);
}
}
return out;
};
// ---- CORS Specific Utils ---- //
//enable CORS on server
testUtils.enableCORS = function (dburl, callback) {
var host = 'http://' + dburl.split('/')[2] + '/';
PouchDB.ajax({
url: host + '_config/httpd/enable_cors',
json: false,
method: 'PUT',
body: '"true"'
}, function (err, resBody, req) {
PouchDB.ajax({
url: host + '_config/cors/origins',
json: false,
method: 'PUT',
body: '"http://127.0.0.1:8000"'
}, function (err, resBody, req) {
callback(err, req);
});
});
};
//enable CORS Credentials on server
testUtils.enableCORSCredentials = function (dburl, callback) {
var host = 'http://' + dburl.split('/')[2] + '/';
PouchDB.ajax({
url: host + '_config/cors/credentials',
method: 'PUT',
body: '"true"',
json: false
}, function (err, resBody, req) {
callback(err, req);
});
};
//disable CORS
testUtils.disableCORS = function (dburl, callback) {
var host = 'http://' + dburl.split('/')[2] + '/';
PouchDB.ajax({
url: host + '_config/cors/origins',
json: false,
method: 'PUT',
body: '"*"'
}, function (err, resBody, req) {
PouchDB.ajax({
url: host + '_config/httpd/enable_cors',
json: false,
method: 'PUT',
body: '"false"'
}, function (err, resBody, req) {
callback(err, req);
});
});
};
//disable CORS Credentials
testUtils.disableCORSCredentials = function (dburl, callback) {
var host = 'http://' + dburl.split('/')[2] + '/';
PouchDB.ajax({
url: host + '_config/cors/credentials',
method: 'PUT',
body: '"false"',
json: false
}, function (err, resBody, req) {
callback(err, req);
});
};
//create admin user and member user
testUtils.setupAdminAndMemberConfig = function (dburl, callback) {
var host = 'http://' + dburl.split('/')[2] + '/';
PouchDB.ajax({
url: host + '_users/org.couchdb.user:TestUser',
method: 'PUT',
body: {
_id: 'org.couchdb.user:TestUser',
name: 'TestUser',
password: 'user',
roles: [],
type: 'user'
}
}, function (err, resBody, req) {
PouchDB.ajax({
url: host + '_config/admins/TestAdmin',
json: false,
method: 'PUT',
body: '"admin"'
}, function (err, resBody, req) {
callback(err, req);
});
});
};
//delete admin and member user
testUtils.tearDownAdminAndMemberConfig = function (dburl, callback) {
var host = 'http://' + dburl.split('/')[2] + '/';
var headers = {};
var token = btoa('TestAdmin:admin');
headers.Authorization = 'Basic ' + token;
PouchDB.ajax({
url: host + '_config/admins/TestAdmin',
method: 'DELETE',
headers: headers,
json: false
}, function (err, resBody, req) {
PouchDB.ajax({
url: host + '_users/org.couchdb.user:TestUser',
method: 'GET',
body: '"admin"'
}, function (err, resBody, req) {
if (resBody) {
PouchDB.ajax({
url: host + '_users/org.couchdb.user:TestUser?rev=' + resBody._rev,
method: 'DELETE',
json: false
}, function (err, resBody, req) {
callback(err, req);
});
} else {
callback(err, req);
}
});
});
};
testUtils.deleteCookieAuth = function (dburl, callback_) {
var host = 'http://' + dburl.split('/')[2] + '/';
PouchDB.ajax({
method: 'DELETE',
url: host + '_session',
withCredentials: true,
json: false
}, callback_);
};
testUtils.cleanUpCors = function (dburl, callback_) {
if (testUtils.PERSIST_DATABASES) {
return;
}
if (typeof module !== 'undefined' && module.exports) {
testUtils.disableCORS(dburl, function () {
PouchDB.destroy(dburl, callback_);
});
} else {
testUtils.disableCORS(dburl.replace('5984', '2020'), function () {
PouchDB.destroy(dburl.replace('5984', '2020'), callback_);
});
}
};
var testDir;
if (typeof module !== 'undefined' && module.exports) {
global.PouchDB = require('../lib');
if (process.env.LEVEL_ADAPTER || process.env.LEVEL_PREFIX) {
var defaults = {};
if (process.env.LEVEL_ADAPTER) {
defaults.db = require(process.env.LEVEL_ADAPTER);
console.log('Using client-side leveldown adapter: ' +
process.env.LEVEL_ADAPTER);
}
if (process.env.LEVEL_PREFIX) {
defaults.prefix = process.env.LEVEL_PREFIX;
console.log('Using client-side leveldown prefix: ' + defaults.prefix);
}
global.PouchDB = global.PouchDB.defaults(defaults);
}
if (typeof process !== 'undefined') {
testDir = process.env.TESTS_DIR ? process.env.TESTS_DIR : './tmp';
testDir = testDir.slice(-1) === '/' ? testDir : testDir + '/';
global.PouchDB.prefix = testDir + global.PouchDB.prefix;
require('../lib/adapters/leveldb').use_prefix = true;
require('bluebird').onPossiblyUnhandledRejection(function (e, promise) {
throw e;
});
}
module.exports = testUtils;
}