-
Notifications
You must be signed in to change notification settings - Fork 0
/
couch-down.js
322 lines (254 loc) · 7.89 KB
/
couch-down.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
'use strict'
var url = require('url')
var http = require('http')
var https = require('https')
var util = require('util')
var debug = require('debug')('couchdown')
var xtend = require('xtend')
var _findIndex = require('lodash.findindex')
var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
var unwrapValue = require('./unwrap-value')
var joinPath = require('./join')
var CouchIterator = require('./couch-iterator')
var dbRE = /^[a-z]+[a-z0-9_$()+-/]*$/
var httpModules = {
http: http,
https: https
}
function CouchDown (location) {
if (!(this instanceof CouchDown)) {
return new CouchDown(location)
}
var urlParts = url.parse(location)
if (!urlParts.protocol) {
throw new Error(location + ' must contain a protocol')
}
this.reqModule = httpModules[urlParts.protocol.substr(0, urlParts.protocol.length - 1)]
var server = url.format({protocol: urlParts.protocol, host: urlParts.host, auth: urlParts.auth})
var db = urlParts.pathname.substr(1)
if (!dbRE.test(db)) {
throw new Error(db + ' contains invalid characters. Please see http://docs.couchdb.org/en/1.6.1/api/database/common.html#put--db')
}
AbstractLevelDOWN.call(this, location)
this._serverURL = server
this._database = encodeURIComponent(db)
debug('Server URL', server)
debug('Database name', db)
}
util.inherits(CouchDown, AbstractLevelDOWN)
CouchDown.prototype._open = function (options, cb) {
this.valueEncoding = options.valueEncoding
this.keyEncoding = options.keyEncoding
this.createIfMissing = options.createIfMissing
this.errorIfExists = options.errorIfExists
this.wrapJSON = options.wrapJSON || false
var self = this
if (this.keyEncoding === 'ucs2' || this.keyEncoding === 'utf16le') {
throw new Error(this.keyEncoding + ' does not work with CouchDB, please choose a different encoding')
}
this._request(null, 'PUT', null, true, function (err, body) {
if (err && err.type === 'file_exists') {
if (self.errorIfExists) {
debug('Database exists, errorIfExists set though so time to bail')
return cb(new Error('Database already exists at ' + url.resolve(self._serverURL, self._database)))
}
return cb()
}
cb(err)
})
}
CouchDown.prototype._put = function (key, val, options, cb) {
var self = this
var valueEncoding = options.valueEncoding || this.valueEncoding
var keyEncoding = options.keyEncoding || this.keyEncoding
key = key.toString(keyEncoding)
if (valueEncoding === 'json' && !this.wrapJSON) {
debug('we are not wrapping json objects, so just put the object')
return this._putWithRev(key, val, valueEncoding, cb)
}
this._getRev(key, function (err, rev) {
var valueWrapper = {data: val}
if (rev) {
valueWrapper._rev = rev
}
debug('_rev retrieved from server', rev)
self._putWithRev(key, valueWrapper, valueEncoding, cb)
})
}
CouchDown.prototype._putWithRev = function (key, value, valueEncoding, cb) {
var self = this
this._request(key, 'PUT', value, false, function (err, body) {
if (err) {
debug('Error in PUT', err, body)
return cb(err)
}
unwrapValue(body, valueEncoding, self.wrapJSON, cb)
})
}
CouchDown.prototype._get = function (key, options, cb) {
var self = this
var valueEncoding = options.valueEncoding || this.valueEncoding
var keyEncoding = options.keyEncoding || this.keyEncoding
key = key.toString(keyEncoding)
this._request(key, 'GET', null, false, function (err, body) {
if (err) {
debug('Error in GET', body)
return cb(err)
}
unwrapValue(body, valueEncoding, self.wrapJSON, cb)
})
}
CouchDown.prototype._del = function (key, options, cb) {
var self = this
var keyEncoding = options.keyEncoding || this.keyEncoding
key = key.toString(keyEncoding)
var deleteCB = function (err, body) {
if (err) {
debug('Error in DELETE', err, body)
return cb(err)
}
debug('DELETE complete', body)
return cb()
}
if (/^.+\?rev\=.+$/.test(key)) {
return self._request(key, 'DELETE', null, true, deleteCB)
}
this._getRev(key, function (err, rev) {
if (err) {
debug('Error in getting document revision for delete', err, key, rev)
return cb(err)
}
if (!rev) {
debug('There is no _rev available for', key)
return cb(new Error('No _rev available for ' + key))
}
var deleteKey = [key, '?rev=', rev].join('')
self._request(deleteKey, 'DELETE', null, true, deleteCB)
})
}
CouchDown.prototype._batch = function (ops, options, cb) {
var self = this
var valueEncoding = options.valueEncoding || this.valueEncoding
var keyEncoding = options.keyEncoding || this.keyEncoding
var needRevs = ops
.filter(function (op) {
return !op.value._rev
})
.map(function (op) {
return op.key
})
var bulkOps = ops.map(function (op) {
var valEnc = op.valueEncoding || valueEncoding
var keyEnc = op.keyEncoding || keyEncoding
if (valEnc !== 'json' || self.wrapJSON) {
op.value = {data: op.value}
}
if (valEnc === 'json' && typeof op.value === 'string') {
op.value = JSON.parse(op.value)
}
var val = xtend({id: op.key.toString(keyEnc)}, op.value)
if (op.type === 'del') {
val._deleted = true
}
return val
})
if (needRevs.length > 0) {
return this._request('_all_docs', 'POST', {keys: needRevs}, true, function (err, revs) {
if (err) {
debug('Unable to get missing _revs on batch op', err)
return cb(err)
}
if (revs.docs) {
revs.forEach(function (rev) {
var idx = _findIndex(bulkOps, {_id: rev.key})
ops[idx]._rev = rev._rev
})
}
self._processBatch(bulkOps, cb)
})
}
this._processBatch(bulkOps, cb)
}
CouchDown.prototype._processBatch = function (ops, cb) {
var doc = {
docs: ops,
all_or_nothing: true
}
this._request('_bulk_docs', 'POST', doc, true, function (err) {
if (err) {
debug('Unable to batch put', err)
return cb(err)
}
cb()
})
}
CouchDown.prototype._iterator = function (options) {
return new CouchIterator(this, options)
}
CouchDown.prototype._request = function (key, method, payload, parseBody, extraHeaders, cb) {
var server = url.resolve(this._serverURL, this._database)
if (payload && typeof payload !== 'string') {
try {
payload = JSON.stringify(payload)
} catch (err) {
debug('Cannot stringify payload', err, payload)
return cb(err)
}
}
if (typeof extraHeaders === 'function') {
cb = extraHeaders
extraHeaders = {}
}
if (key) {
server = url.resolve(this._serverURL, joinPath(this._database, key))
}
var defaultHeaders = {
'Content-Type': 'application/json'
}
var headers = xtend(defaultHeaders, extraHeaders)
var opts = xtend(url.parse(server), {
method: method,
headers: headers
})
debug('Request generated', method, url.format(opts), payload, opts.headers)
var req = this.reqModule.request(opts, function (res) {
var buf = []
var err = null
res.on('data', function (chunk) {
buf.push(chunk.toString('utf8'))
})
res.on('end', function () {
var body = buf.join('')
var etag = ''
if (parseBody) {
try {
body = JSON.parse(body)
} catch (err) {
return cb(err)
}
}
if (res.statusCode !== 200 && res.statusCode !== 201) {
err = new Error(body.reason)
err.type = body.error
err.status = res.statusCode
if (res.statusCode === 404) {
err.notFound = true
}
}
if (res.headers.etag) {
etag = res.headers.etag.replace(/\"/g, '')
}
cb(err, body, etag)
})
})
req.end(payload)
}
CouchDown.prototype._getRev = function (key, cb) {
this._request(key, 'HEAD', null, false, function (err, body, rev) {
if (err && err.statusCode !== 404) {
return cb(err)
}
cb(null, rev)
})
}
module.exports = CouchDown