-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp-p.js
More file actions
120 lines (96 loc) · 2.56 KB
/
http-p.js
File metadata and controls
120 lines (96 loc) · 2.56 KB
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
const request = require('request')
module.exports = class HttpP {
constructor (url) {
this.url = url
}
reset (done) {
request.delete(this.url, () => {
request.put(this.url, () => done(null))
})
}
// get document ids
read (options = {}, done) {
if (typeof options === 'function') {
done = options
options = {}
}
return options.revs ? this._readDocsWithRevs(options, done) : this._readDocs(options, done)
}
_readDocsWithRevs (options = {}, done) {
const qs = {}
if (options.conflicts) {
qs.include_docs = true
qs.conflicts = true
}
return request.get({
url: `${this.url}/_all_docs`,
json: true,
qs
}, (error, response, body) => {
if (error) return done(error)
const docs = body.rows.map(row => ({ id: row.id, rev: row.value.rev }))
const conflicts = options.conflicts && body.rows.reduce((memo, row) => {
memo[row.id] = row.doc._conflicts
return memo
}, {})
request.post({
url: `${this.url}/_bulk_get`,
json: true,
body: {
docs
},
qs: {
revs: true
}
}, (error, response, body) => {
if (error) return done(error)
const docs = body.results.reduce((memo, { docs }) => memo.concat(docs.map(doc => doc.ok)), [])
if (options.conflicts) {
docs.forEach(doc => {
doc._conflicts = conflicts[doc._id]
})
}
done(null, docs)
})
})
}
_readDocs (options = {}, done) {
const qs = {
include_docs: true
}
if (options.conflicts) qs.conflicts = true
return request.get({
url: `${this.url}/_all_docs`,
json: true,
qs
}, (error, response, body) => {
if (error) return done(error)
const ids = body.rows.map(row => row.doc)
done(null, ids)
})
}
// write documents
//
// options can be
// * new_edits: if set to false, do not generate new revisions, use provided rev
write (docs, options = {}, done) {
if (typeof options === 'function') {
done = options
options = {}
}
if (!Array.isArray(docs)) docs = [docs]
const body = { docs }
if (options.new_edits === false) {
if (docs.find(doc => !doc._rev)) throw (new Error('no _rev given'))
body.new_edits = false
}
const callback = done
? (error, response, body) => done(error, body.length ? body : null)
: null
return request.post({
url: `${this.url}/_bulk_docs`,
json: true,
body
}, callback)
}
}