-
Notifications
You must be signed in to change notification settings - Fork 2
/
rest_fetch.js
30 lines (28 loc) · 992 Bytes
/
rest_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
import OAuth from '../oauth';
import {t} from 'i18n';
const T = (s, opts) => t('errors.'+s, opts);
export default function(fetch) {
return function(url, options) {
return fetch(url, options).then((resp) => {
if (resp.status >= 200 && resp.status < 300) {
if (resp.status !== 204 /* no content */) {
return resp.json();
}
} else if (resp.status === 401) {
// need (re-)authentication
// @todo make it more flexible what to do here
new OAuth().request();
// unreachable code
throw new Error(T('authentication_required'));
} else {
// throw error with message from json when available
const defaultDescription = T('general', {text: resp.statusText, code: resp.status});
return resp.json().then((json) => {
throw new Error(json.error_description || defaultDescription);
}, () => {
throw new Error(defaultDescription);
});
}
});
}
}