-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathajax.js
83 lines (72 loc) · 2.18 KB
/
ajax.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
import {getOr, isNil} from 'lodash/fp';
import {Auth} from './auth/auth';
import {Config} from './config';
import {spinnerService} from './spinner-service';
import {StackdriverReporter} from './stackdriverReporter';
import axios from 'axios';
//define axios interceptor
//to log out user and redirect to home when response has 401 status
//return responses with statuses in the 200s and reject the rest
const redirectOnLogout = () => {
Auth.signOut();
window.location.href = `/home?redirectTo=${window.location.pathname}`;
};
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
// Default to a 502 when we can't get a real response object.
const status = getOr(502)('response.status')(error);
if (status === 401) {
redirectOnLogout();
}
const reportUrl = getOr(null)('response.config.url')(error);
if (!isNil(reportUrl) && status >= 500) {
reportError(reportUrl, status);
}
return Promise.reject(error);
});
export const getApiUrl = async() => {
return await Config.getApiUrl();
};
export const getBardApiUrl = async() => {
return await Config.getBardApiUrl();
};
export const getOntologyUrl = async() => {
return await Config.getOntologyApiUrl();
};
export const getECMUrl = async() => {
return await Config.getECMUrl();
};
export const fetchOk = async (...args) => {
//TODO: Remove spinnerService calls
spinnerService.showAll();
const res = await fetch(...args);
if (!res.ok && res.status === 401) {
redirectOnLogout();
}
if (res.status >= 400) {
await reportError(args[0], res.status);
}
spinnerService.hideAll();
return res.ok ? res : Promise.reject(res);
};
export const fetchAny = async (...args) => {
//TODO: Remove spinnerService calls
spinnerService.showAll();
const res = await fetch(...args);
if (!res.ok && res.status === 401) {
redirectOnLogout();
}
if (res.status >= 500) {
await reportError(args[0], res.status);
}
spinnerService.hideAll();
return res;
};
export const reportError = async (url, status) => {
const msg = 'Error fetching response: '
.concat(JSON.stringify(url))
.concat('Status: ')
.concat(status);
await StackdriverReporter.report(msg);
};