-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (67 loc) · 2.17 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
var Promise = require('bluebird');
var request = require('request');
/**
* Define SuperModel Data Source - CouchDB
*/
var SuperModelCouchdb = function(options){
return {
name: 'couchdb',
source: {
find: function(id, cb){
return Promise.promisify(getDocument, {context: this})(id).bind(this).then(function(data){
this.import(data);
if( typeof cb == 'function' ){
cb.call(this);
}
return;
}, function(err){
cb.call(this, err);
throw new Error(err);
});
},
save: function(cb){
return Promise.promisify(saveDocument, {context: this})().bind(this).then(function(body){
this.set('_id', body.id);
this.set('_rev', body.rev);
if( typeof cb == 'function' ){
cb.call(this);
}
return;
}, function(err){
cb.call(this, err);
throw new Error(err);
});
},
_options: options
}
};
};
function getDocument(id, cb){
request({
method: 'GET',
url: this._options.protocol + '://' + this._options.host + ':' + this._options.port + '/' + this._options.database + '/' + id,
json: true
}, function(err, res, body){
if( err ){
return cb('Request Error: ' + err);
}
return cb(null, body);
});
}
function saveDocument(cb){
request({
method: 'PUT',
url: this._options.protocol + '://' + this._options.host + ':' + this._options.port + '/' + this._options.database + (this.get('_id') ? '/' + this.get('_id') : ''),
json: this.export()
}, function(err, res, body){
if( err ){
return cb('Request Error: ' + err);
}
if( body.ok === true ){
cb(null, body);
}else{
return cb('CouchDB ' + body.error + ': ' + body.reason);
}
}.bind(this));
}
module.exports = SuperModelCouchdb;