forked from flatiron/resourceful
/
index.js
222 lines (190 loc) · 6.32 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
/*
* couchdb/index.js: CouchDB engine wrapper
*
* (C) 2011 Nodejitsu Inc.
* MIT LICENCE
*
*/
var url = require('url'),
cradle = require('cradle'),
resourceful = require('../../../resourceful'),
render = require('./view').render,
filter = require('./view').filter;
var Couchdb = exports.Couchdb = function Couchdb(config) {
if (config.uri) {
var parsed = url.parse('couchdb://' + config.uri);
config.uri = parsed.hostname;
config.port = parseInt(parsed.port, 10);
config.database = (parsed.pathname || '').replace(/^\//, '');
}
this.connection = new(cradle.Connection)({
host: config.host || config.uri || '127.0.0.1',
port: config.port || 5984,
raw: true,
cache: false,
secure: config.secure,
auth: config && config.auth || null
}).database(config.database || resourceful.env);
this.cache = new resourceful.Cache();
};
Couchdb.prototype.protocol = 'couchdb';
Couchdb.prototype.load = function (data) {
throw new(Error)("Load not valid for couchdb engine.");
};
Couchdb.prototype.request = function (method) {
var args = Array.prototype.slice.call(arguments, 1);
return this.connection[method].apply(this.connection, args);
};
Couchdb.prototype.head = function (id, callback) {
return this.request('head', id, callback);
};
Couchdb.prototype.get = function (id, callback) {
return this.request.call(this, 'get', id, function (e, res) {
if (e) {
e.status = e.headers.status;
return callback(e);
}
return Array.isArray(id)
? callback(null, res.rows.map(function (r) { return r.doc; }))
: callback(null, res);
});
};
Couchdb.prototype.put = function (id, doc, callback) {
return this.request('put', id, doc, function (e, res) {
if (e) return callback(e);
res.status = 201;
callback(null, resourceful.mixin({}, doc, res));
});
};
Couchdb.prototype.post = Couchdb.prototype.create = function (doc, callback) {
return this.request('post', doc, function (e, res) {
if (e) return callback(e);
res.status = 201;
callback(null, resourceful.mixin({}, doc, res));
});
};
Couchdb.prototype.save = function (id, doc, callback) {
var args = Array.prototype.slice.call(arguments, 0),
callback = args.pop(),
doc = args.pop();
// if there's an ID left in args after popping off the callback and
// the doc, then we need to PUT, otherwise create a new record thru POST
if (args.length) {
return this.put.apply(this, arguments);
}
// checks for presence of _id in doc, just in case the caller forgot
// to add an id as first argument
if (doc._id) {
return this.put.apply(doc._id, doc, callback);
} else {
return this.post.call(this, doc, callback);
}
};
Couchdb.prototype.update = function (id, doc, callback) {
return this.cache.has(id)
? this.put(id, resourceful.mixin({}, this.cache.get(id).toJSON(), doc), callback)
: this.request('merge', id, doc, callback);
};
Couchdb.prototype.destroy = function () {
var that = this,
args = Array.prototype.slice.call(arguments),
id = args[0],
rev;
if (Array.isArray(id)) {
rev = id[1];
id = id[0];
}
if (rev) {
return this.request.apply(this, ['remove', id, rev, callback]);
}
if (this.cache.has(id)) {
args.splice(1, -1, this.cache.get(id)._rev);
return this.request.apply(this, ['remove'].concat(args));
}
this.head(id, function (e, headers, res) {
if (res === 404 || !headers['etag']) {
e = e || { reason: 'not_found' };
}
if (headers.etag) {
args.splice(1, -1, headers.etag.slice(1, -1));
return that.request.apply(that, ['remove'].concat(args));
} else { args.pop()(e) }
});
};
Couchdb.prototype.view = function (path, opts, callback) {
return this.request.call(this, 'view', path, opts, function (e, res) {
if (e) return callback(e);
callback(null, res.rows.map(function (r) {
// With `include_docs=true`, the 'doc' attribute is set instead of 'value'.
return r.doc || r.value;
}));
});
};
Couchdb.prototype.find = function (conditions, callback) {
mapFunction = "function (doc) { var obj = " + JSON.stringify(conditions) + "; if (function () { ";
mapFunction+= "for (var k in obj) { if (obj[k] !== doc[k]) return false; } return true;";
mapFunction+= "}()) { emit(doc._id, doc); }}";
this.connection.temporaryView({
map: mapFunction
}, function (e, res) {
if (e) return callback(e);
callback(null, res.rows.map(function (r) {
// With `include_docs=true`, the 'doc' attribute is set instead of 'value'.
return r.doc || r.value;
}));
});
};
Couchdb.prototype.filter = function (name, data) {
return filter.call(data.resource, name, data.options, data.filter);
};
Couchdb.prototype.sync = function (factory, callback) {
var that = this,
id = '_design/' + factory.resource;
factory._design = factory._design || {};
factory._design._id = id;
if (factory._design._rev) return callback(null);
this.connection.head(id, function (e, headers, status) {
if (!e && headers.etag) {
factory._design._rev = headers.etag.slice(1, -1);
}
that.connection.put(id, factory._design, function (e, res) {
if (e) {
if (e.reason === 'no_db_file') {
that.connection.create(function () {
that.sync(factory, callback);
});
}
else {
/* TODO: Catch errors here. Needs a rewrite, because of the race */
/* condition, when the design doc is trying to be written in parallel */
callback(e);
}
}
else {
// We might not need to wait for the document to be
// persisted, before returning it. If for whatever reason
// the insert fails, it'll just re-attempt it. For now though,
// to be on the safe side, we wait.
factory._design._rev = res.rev;
callback(null, factory._design);
}
});
});
};
//
// Relationship hook
//
Couchdb._byParent = function (factory, parent, rfactory) {
factory.filter('by' + parent, { include_docs: true }, resourceful.render({
map: function (doc) {
if (doc.resource === $resource) {
for (var i = 0; i < doc.$children.length; i++) {
emit(doc._id, { _id: doc.$children[i] });
}
}
}
}, {
resource: JSON.stringify(parent),
children: (''+factory.resource).toLowerCase() + '_ids'
}));
};