-
Notifications
You must be signed in to change notification settings - Fork 21
/
xhr.js
76 lines (64 loc) · 1.58 KB
/
xhr.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
'use strict';
var xhr = require('xhr');
var sum = require('hash-sum');
var temporize = require('temporize');
function request (url, options, end) {
var displaced = typeof options === 'function';
var hasUrl = typeof url === 'string';
var user;
var done = displaced ? options : end;
if (hasUrl) {
if (displaced) {
user = { url: url };
} else {
user = options;
user.url = url;
}
} else {
user = url;
}
var o = {
headers: { Accept: 'application/json' }
};
Object.keys(user).forEach(overwrite);
var req;
var hash = sum(o) + ':' + o.url;
var cached = true;
temporize({
name: hash,
seconds: 1,
load: load
}, loaded);
return req;
function overwrite (prop) {
o[prop] = user[prop];
}
function load (done) {
global.DEBUG && global.DEBUG('[xhr] %s %s', o.method || 'GET', o.url);
cached = false;
var result = xhr(o, handle);
done(null, result);
return result;
}
function loaded (result) {
if (cached) {
global.DEBUG && global.DEBUG('[xhr] %s %s (cache)', o.method || 'GET', o.url);
}
req = result;
}
function handle (err, res, body) {
if (err && !req.getAllResponseHeaders()) {
global.DEBUG && global.DEBUG('[xhr] %s %s (aborted)', o.method || 'GET', o.url);
done(new Error('aborted'), null, res);
} else {
try {
res.body = body = JSON.parse(body);
} catch (e) {
// suppress
}
global.DEBUG && global.DEBUG('[xhr] %s %s (done)', o.method || 'GET', o.url);
done(err, body, res);
}
}
}
module.exports = request;