forked from olebedev/go-duktape-fetch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetch.js
110 lines (81 loc) · 2 KB
/
fetch.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
/**
* fetch.js
*
* a request API compatible with window.fetch
*/
var Headers = require('node-fetch/lib/headers');
var assign = require('lodash/object/assign');
module.exports = Fetch;
/**
* Fetch class
*
* @param Mixed url Absolute url or Request instance
* @param Object opts Fetch options
* @return Promise
*/
function Fetch(url, o) {
// allow call as function
if (!(this instanceof Fetch))
return new Fetch(url, options);
// allow custom promise
if (!Fetch.Promise) {
throw new Error('native promise missing, set Fetch.Promise to your favorite alternative');
};
if (!url) {
throw new Error('url parameter missing');
};
var options = o || {};
// wrap http.request into fetch
return new Fetch.Promise(function(resolve, reject) {
// normalize headers
var headers = new Headers(options.headers || {});
if (!headers.has('user-agent')) {
headers.set('user-agent', 'golang-fetch/0.0 (+https://github.com/olebedev/go-duktape-fetch)');
}
headers.set('connection', 'close');
if (!headers.has('accept')) {
headers.set('accept', '*/*');
}
options.headers = headers.raw();
// send a request
var res = Fetch.goFetchSync(url, options);
if (res instanceof Error) {
reject(res);
} else {
res.url = url;
resolve(new Response(res));
}
});
};
/**
* Response class
*
* @param Object opts Response options
* @return Void
*/
function Response(r) {
assign(this, r)
this.ok = this.status >= 200 && this.status < 300;
}
/**
* Decode response as json
*
* @return Promise
*/
Response.prototype.json = function() {
return this.text().then(function(text) {
return JSON.parse(text);
});
}
/**
* Decode response body as text
*
* @return Promise
*/
Response.prototype.text = function() {
var _this = this;
return new Fetch.Promise(function(resolve, reject) {
resolve(_this.body);
});
}
Fetch.Promise = typeof Promise !== 'undefined' ? Promise : require('when').Promise;