-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcushion.js
496 lines (433 loc) · 13.9 KB
/
cushion.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
'use strict';
var http = require('http'),
https = require('https'),
defaultOptions = require('./config.js'),
Database = require('./database.js').Database,
UserApi = require('./user.js').User;
/**
* create connection to a couchdb
*
* @param {string} [host=this._options.host] host address
* @param {number} [port=this._options.port] port
* @param {string} [username=this._options.username] username for authorization
* @param {string} [password=this._options.password] password for authorization
* @param {object} additional additional options:
* {boolean} [secure=false] set this to true, if you want https-connections
* {string} [path=''] set an additional path, if you want to connect through
* this (e.g. a proxy, because of connecting from browser)
*/
var cushion = function(host, port, username, password, additional) {
additional = additional || {};
this._methodMatch = /^GET|PUT|POST|DELETE|HEAD|COPY$/i;
this._options = {
'host': host || defaultOptions.host,
'port': port || defaultOptions.port,
'username': username || defaultOptions.username,
'password': password || defaultOptions.password,
'secure': additional.secure || defaultOptions.secure,
'path': (additional.path) ? additional.path + '/' : defaultOptions.path
};
if (this._options.secure === true) {
this._http = https;
} else {
this._http = http;
}
};
/**
* returns a list of active tasks
*
* @param {function(error, activeTasks)} callback function that will called,
* after getting the list of active tasks or if there was an error
*/
cushion.prototype.activeTasks = function(callback) {
this.request({
'method': 'GET',
'path': '_active_tasks',
'callback': callback
});
};
/**
* set or get configuration params
* if you set:
* one param: you will get the complete configuration
* two params: you will get all options of the specific section
* three params: you will get the content of the specific option
* four params: you set a specific option to the new value, or you delete the
* given option, if you set value to null
*
* @param {string|function(error, configuration)} sectionOrCallback a section of
* different config params or function that will be called, after getting
* the whole configuration or if there was an error
* @param {?string|function(error, options)} optionOrCallback an specific option
* or a function, that will be called, after getting the options of the
* section of if there was an error
* @param {?string|function(error, value)} valueOrCallback the new value for the
* option or function that will be called, after getting the content of the
* option; if you set the value to null, option will be deleted
* @param {?function(error, saved)} callback function that will be called after
* saving the new value, or if there was an error
*/
cushion.prototype.config = function(
sectionOrCallback,
optionOrCallback,
valueOrCallback,
callback
) {
var section = (typeof(sectionOrCallback) === 'string') ?
sectionOrCallback :
null,
option = (typeof(optionOrCallback) === 'string') ?
optionOrCallback :
null,
value = (
typeof(valueOrCallback) === 'string' ||
typeof(valueOrCallback) === 'number' ||
valueOrCallback === null
) ? valueOrCallback : undefined,
options;
callback = callback ||
valueOrCallback ||
optionOrCallback ||
sectionOrCallback;
options = {
'method': (value !== undefined) ?
((value === null) ? 'DELETE' : 'PUT') :
'GET',
'path': '_config' +
((section) ? '/' + section : '') +
((option) ? '/' + option : ''),
'callback': function(error, response) {
if (error) {
response = null;
} else {
response = (value !== undefined) ? true : response;
}
callback(error, response);
}
};
// do we set a new value?
if (typeof(value) === 'string' || typeof(value) === 'number') {
options.body = '"' + value + '"';
}
this.request(options);
};
/**
* creates an admin
*
* @param {string} name name of the admin account
* @param {string} password password of the admin account
* @param {function(error, created)} callback function that will be called after
* creating the admin account, or if there was an error
*/
cushion.prototype.createAdmin = function(name, password, callback) {
// first we have to create a new option at the config
this.config('admins', name, password, (function(error, created) {
// after that we have to create a user document
if (created === true) {
this.database('_users').document('org.couchdb.user:' + name)
.body('name', name)
.body('type', 'user')
.body('roles', [])
.save(function(error) {
if (error) {
callback(error, null);
} else {
callback(error, true);
}
});
} else {
callback(error, null);
}
}).bind(this));
};
/**
* gives a connection to a specific database
*
* @param {string} name name of the database
* @return {Object} the database object
*/
cushion.prototype.database = function(name) {
return new Database(name, this);
};
/**
* deletes an admin
*
* @param {string} name username of the admin
* @param {function(error, deleted)} callback function that will be called,
* after deleting the admin account, or if there was an error
*/
cushion.prototype.deleteAdmin = function(name, callback) {
// first we have to delete the admin option
this.config('admins', name, null, (function(error, deleted) {
// after that we have to delete the user document
var database,
document;
if (deleted === true) {
database = this.database('_users');
document = database.document('org.couchdb.user:' + name);
document.load(function(error, document) {
if (document) {
document.destroy(function(error, document) {
if (document) {
callback(null, true);
} else {
callback(error, null);
}
});
} else {
callback(error, null);
}
});
} else {
callback(error, null);
}
}).bind(this));
};
/**
* retrieving a list of databases
*
*
* @param {boolean|function(error, databases)} noCouchRelatedOrCallback filters
* all couch related databases, so the list has only databases which a user
* has set up or function that will be called after retrieving a list of
* databases, or if there was an error
* @param {?function()} callback function that will be called after retrieving a
* list of databases, or if there was an error
*/
cushion.prototype.listDatabases = function(noCouchRelatedOrCallback, callback) {
var noCouchRelated = (callback) ? noCouchRelatedOrCallback : null;
callback = callback || noCouchRelatedOrCallback;
this.request({
'method': 'GET',
'path': '_all_dbs',
'callback': (function (error, response) {
if (error === null && response !== null) {
// filter couch related databases, if user want's so
if (noCouchRelated === true) {
response = response.filter(function(dbName) {
return (dbName[0] !== '_');
});
}
// create database objects
response = response.map(function(dbName) {
return this.database(dbName);
}, this);
}
callback(error, response);
}).bind(this)
});
};
/**
* returns the tail of the server's log file
*
* @param {number|function(error, log)} bytesOrCallback number of bytes how many
* do you want from the tail or function that will be called, after getting
* the log or if there was an error
* @param {?function(error, log)} callback function that will be called, after
* getting the log or if there was an error
*/
cushion.prototype.log = function(bytesOrCallback, callback) {
var bytes = (arguments.length > 1) ? bytesOrCallback : null;
callback = callback || bytesOrCallback;
this.request({
'method': 'GET',
'path': '_log' + ((bytes) ? '?bytes=' + bytes : ''),
'callback': callback
});
};
/**
* set or get connection options
* if you set:
* no param: you will get all options
* one params: you will get one particular option
* two params: you will set one particular option
*
* @param {?string} option name of option
* @param {?string|number} value value of option
* @return {object|string|number|undefined} object representing all options or
* value of option or undefined, if option does not exist
*/
cushion.prototype.option = function(option, value) {
var response;
option = (arguments.length > 0) ? option : null;
if (option) {
if (value && this._options[option]) {
this._options[option] = value;
}
response = this._options[option];
} else {
response = this._options;
}
return response;
};
/**
* wrapper function for any request to the couchdb
*
* @param {Function} callback function that will be called after all data events
* @param {http.ClientResponse} response the http response object
*/
cushion.prototype._request = function(callback, response) {
var content = '';
response.on('data', function(chunk) {
content += chunk;
});
response.on('end', (function() {
var validJson = false;
try {
if (
response.headers['content-type'] === 'application/json' &&
content.length > 0
) {
content = JSON.parse(content);
}
validJson = true;
} catch(error) {
callback(error, null, null);
}
if (validJson === true) {
if (response.statusCode === 404 && content.length === 0) {
content = {
'error': 'not_found',
'reason': 'missing'
};
}
callback(
(content.error) ? content : null,
(!content.error) ? content : null,
response.headers || null
);
}
}).bind(this));
};
/**
* sends a request to the couch
*
* @param {object} properties options for the request
* method: {string} http method, can be GET, PUT, POST, DELETE, HEAD, COPY
* path: {string} uri path after domain
* headers: {Object} key/value-pairs of additional http headers
* body: {Object|Array} additional body
* callback: {function(error, response)} function that will be called,
* after getting the response or if there was an error
*/
cushion.prototype.request = function(properties) {
var options = {
'host': this._options.host,
'port': this._options.port,
'method': (
typeof(properties.method) === 'string' &&
properties.method.match(this._methodMatch) !== null
) ?
properties.method :
'GET',
'path': '/' + this._options.path + (properties.path || ''),
'auth': this._options.username + ':' + this._options.password,
'headers': properties.headers || {}
},
request;
// make sure, that we get application/json response from couchdb
options.headers.Accept = options.headers.Accept || '*/*,application/json';
options.headers['Content-Type'] = options.headers['Content-Type'] ||
'application/json';
// set up request object
request = this._http.request(
options,
this._request.bind(this, properties.callback)
);
// define callback, if there is an error
request.on('error', (function(error) {
properties.callback(error, null, null);
}).bind(this));
// adding optional body to the request
if (properties.body) {
if (typeof(properties.body) === 'object') {
request.write(JSON.stringify(properties.body));
} else {
request.write(properties.body);
}
}
// starting request
request.end();
};
/**
* restarts the couchdb
*
* @param {function(error, restart)} callback function that will be called,
* after initializing the restart or if there was an error
*/
cushion.prototype.restart = function(callback) {
this.request({
'method': 'POST',
'path': '_restart',
'callback': function(error, restart) {
if (error && error.code === 'ECONNRESET') {
error = null;
restart = true;
}
callback(error, restart);
}
});
};
/**
* returns server statistics
*
* @param {function(error, stats)} callback function that will be called, after
* getting the statistics of if there was an error
*/
cushion.prototype.stats = function(callback) {
this.request({
'method': 'GET',
'path': '_stats',
'callback': callback
});
};
/**
* get the user object
*
* @return {cushion.User} the user object
*/
cushion.prototype.user = function() {
return new UserApi(this);
};
/**
* returns a list of generated uuids
*
* @param {number|function(error, uuidList)} countOrCallback number of uuids to
* generate or function that will be called, after getting the list of uuids
* or if there was an error
* @param {?function(error, uuidList)} callback function that will be called,
* after getting the list of uuids or if there was an error
*/
cushion.prototype.uuids = function(countOrCallback, callback) {
var count = (arguments.length > 1) ? countOrCallback : null;
callback = callback || countOrCallback;
this.request({
'method': 'GET',
'path': '_uuids' + ((count) ? '?count=' + count : ''),
'callback': function(error, uuidList) {
if (uuidList) {
uuidList = uuidList.uuids;
}
callback(error, uuidList);
}
});
};
/**
* gets the version of the couchdb
*
* @param {function(error, version)} callback function that will be called after
* getting the version, of if there was an error
*/
cushion.prototype.version = function(callback) {
this.request({
'method': 'GET',
'path': '',
'callback': function(error, response) {
if (response !== null) {
response = response.version;
}
callback(error, response);
}
});
};
exports.Connection = cushion;