-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.js
More file actions
101 lines (77 loc) · 2.51 KB
/
request.js
File metadata and controls
101 lines (77 loc) · 2.51 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
// var debug = require('debug')('bootic');
// var uriTemplate = require('uri-templates');
const debug = function(str) { }
import uriTemplate from 'uri-templates';
// import { fetch } from 'node-fetch-polyfill';
// import fetch from 'node-fetch';
// import './fetch-polyfill'
function sendRequest(method, url, params, headers) {
var template, params = params || {}, options = {
// redirect: options.redirect || 'manual',
// keepalive: true,
method : (method || 'get').toUpperCase(),
headers : headers
}
options.headers['Accept'] = 'application/json';
options.headers['Content-Type'] = 'application/json';
// temporary hack
if (params.subdomain) {
params.subdomains = params.subdomain;
delete params.subdomain;
}
if (~url.indexOf('{')) { // templated
// detect required params, the ones not starting with {? or {&
var missingParams = (url.match(/{(?!\?|&)([^}]+)}/g) || []).filter(function(v) {
var name = v.split(/{|}/)[1];
return !params[name];
})
if (missingParams.length)
throw new Error('Missing variables for query: ' + missingParams.join(', '));
template = uriTemplate(url);
url = template.fill(params);
template.varNames.forEach(function(v) {
delete params[v];
})
}
if (Object.keys(params).length > 0) {
// if (template)
// throw new Error('Invalid params: ' + Object.keys(params));
if (['get', 'head'].indexOf(options.method) != -1)
throw new Error('GET or HEAD request, cannot send these params: ' + Object.keys(params));
options.body = JSON.stringify(params);
}
debug(url, JSON.stringify(options).yellow);
return fetch(url, options);
}
function streamData(url, headers, cb, done) {
debug(headers);
return fetch(url, { headers: headers }).then(function(response) {
var obj, reader = response.body.getReader();
if (response.status > 300)
throw new Error('Invalid response code: ' + response.status)
function decode(str) {
var data;
try { data = JSON.parse(str.toString()) } catch(e) { }
return data;
}
function next() {
return reader.read().then(function(result) {
obj = decode(result.value);
if (obj) cb(obj)
if (result.done) throw Error("Looks like we're done.");
return next();
})
}
return next();
}).then(function(result) {
done(null, result)
}).catch(function(err) {
done(err)
});
}
// exports.send = sendRequest;
// exports.stream = streamData;
export {
sendRequest,
streamData
}