-
Notifications
You must be signed in to change notification settings - Fork 0
/
requests.js
72 lines (61 loc) · 1.66 KB
/
requests.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
'use strict';
const fetch = require('./fetch');
const Cache = require('./cache');
const NOW_API_URL = "https://api.zeit.co/now/";
class NowRequest {
/** @return {Promise} */
constructor(path, options) {
return Cache.get(Cache.TOKEN).then(token => {
if (!token) throw "Can't make now() request without a token.";
this.path = path;
this.options = options || {method: 'GET'};
this.token = token;
return this.fetch();
});
}
/** @return {Promise} */
fetch() {
return fetch(this.url(),
this.fetchOptions())
.then(this.fetched.bind(this));
}
/**
* @param {Object} response
* @return {Object}
*/
fetched(response) {
return response.text()
.then(text => JSON.parse(text))
.then(obj => {
if (response.status !== 200) {
if (obj.error) throw new Error(obj.error.message);
throw new Error('Not authorized');
}
return obj;
})
.catch(e => { throw e });
}
/** @return {Object} */
fetchOptions() {
let authOptions = {
headers: {'Authorization': 'Bearer ' + this.token}
};
if (this.options.method === 'POST') {
authOptions.headers['Content-Type'] = 'application/json';
}
return Object.assign(authOptions, this.options);
}
/** @return {String} */
url() {
return NOW_API_URL + this.path;
}
}
/**
* @param {String} path
* @param {Object} options
* @return {Promise}
*/
function now(path, options) {
return new NowRequest(path, options);
}
module.exports.now = now;