This repository was archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy pathrequest-api.js
197 lines (163 loc) · 4.82 KB
/
request-api.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
'use strict'
const Wreck = require('wreck')
const Qs = require('qs')
const ndjson = require('ndjson')
const getFilesStream = require('./get-files-stream')
const isNode = require('detect-node')
// -- Internal
function parseChunkedJson (res, cb) {
const parsed = []
res
.pipe(ndjson.parse())
.on('data', (obj) => {
parsed.push(obj)
})
.on('end', () => {
cb(null, parsed)
})
}
function onRes (buffer, cb, uri) {
return (err, res) => {
if (err) {
return cb(err)
}
const stream = Boolean(res.headers['x-stream-output'])
const chunkedObjects = Boolean(res.headers['x-chunked-output'])
const isJson = res.headers['content-type'] &&
res.headers['content-type'].indexOf('application/json') === 0
if (res.statusCode >= 400 || !res.statusCode) {
const error = new Error(`Server responded with ${res.statusCode}`)
return Wreck.read(res, {json: true}, (err, payload) => {
if (err) {
return cb(err)
}
if (payload) {
error.code = payload.Code
error.message = payload.Message || payload.toString()
}
cb(error)
})
}
if (stream && !buffer) {
return cb(null, res)
}
if (chunkedObjects) {
if (isJson) {
return parseChunkedJson(res, cb)
}
return Wreck.read(res, null, cb)
}
Wreck.read(res, {json: isJson}, cb)
}
}
function requestAPI (config, options, callback) {
options.qs = options.qs || {}
if (Array.isArray(options.files)) {
options.qs.recursive = true
}
if (Array.isArray(options.path)) {
options.path = options.path.join('/')
}
if (options.args && !Array.isArray(options.args)) {
options.args = [options.args]
}
if (options.args) {
options.qs.arg = options.args
}
if (options.files && !Array.isArray(options.files)) {
options.files = [options.files]
}
if (options.qs.r) {
options.qs.recursive = options.qs.r
// From IPFS 0.4.0, it throws an error when both r and recursive are passed
delete options.qs.r
}
options.qs['stream-channels'] = true
let stream
if (options.files) {
stream = getFilesStream(options.files, options.qs)
}
// this option is only used internally, not passed to daemon
delete options.qs.followSymlinks
const port = config.port ? `:${config.port}` : ''
const opts = {
method: 'POST',
uri: `${config.protocol}://${config.host}${port}${config['api-path']}${options.path}?${Qs.stringify(options.qs, {arrayFormat: 'repeat'})}`,
headers: {}
}
if (isNode) {
// Browsers do not allow you to modify the user agent
opts.headers['User-Agent'] = config['user-agent']
}
if (options.files) {
if (!stream.boundary) {
return callback(new Error('No boundary in multipart stream'))
}
opts.headers['Content-Type'] = `multipart/form-data; boundary=${stream.boundary}`
opts.payload = stream
}
return Wreck.request(opts.method, opts.uri, opts, onRes(options.buffer, callback, opts.uri))
}
//
// -- Module Interface
exports = module.exports = function getRequestAPI (config) {
/*
* options: {
* path: // API path (like /add or /config)
* args: // Arguments to the command
* qs: // Opts as query string opts to the command --something
* files: // files to be sent
* buffer: // buffer the request before sending it
* }
*/
const send = function (options, callback) {
if (typeof options !== 'object') {
return callback(new Error('no options were passed'))
}
if (typeof callback !== 'function' && typeof Promise !== 'undefined') {
return new Promise(function (resolve, reject) {
requestAPI(config, options, function (err, res) {
if (err) {
return reject(err)
}
resolve(res)
})
})
}
return requestAPI(config, options, callback)
}
// Wraps the 'send' function such that an asynchronous
// transform may be applied to its result before
// passing it on to either its callback or promise.
send.withTransform = function (transform) {
return function (options, callback) {
if (typeof options !== 'object') {
return callback(new Error('no options were passed'))
}
const p = send(options, wrap(callback))
if (p instanceof Promise) {
return p.then((res) => {
return new Promise(function (resolve, reject) {
transform(null, res, send, function (err, res) {
if (err) {
reject(err)
} else {
resolve(res)
}
})
})
})
} else {
return p
}
function wrap (func) {
if (func) {
return function (err, res) {
transform(err, res, send, func)
}
}
}
}
}
return send
}