-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathapi.js
54 lines (47 loc) · 1.6 KB
/
api.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
import AsyncStorage from '@react-native-community/async-storage';
import axios from 'axios';
import _ from 'lodash';
class API {
static async headers() {
const token = this.getAuthToken();
return {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: 'Bearer' + token,
};
}
getAuthToken = async () => {
try {
const value = await AsyncStorage.getItem('@token');
if (value !== null) {
return value;
}
return '';
} catch (e) {
return '';
}
};
static fetch(options) {
if (options.authorized != false) options.headers = _.merge(this.headers(), options.headers);
return axios(options).catch((errorResponse) => {
var errorMessages = '';
if (!options.silent) {
if (errorResponse.response && errorResponse.response.data.errors) {
errorMessages = _.join(errorResponse.response.data.errors, '\n');
} else if (errorResponse.response && errorResponse.response.data.error) {
errorMessages = errorResponse.response.data.error;
} else if (errorResponse.response && errorResponse.response.data.message) {
errorMessages = errorResponse.response.data.message;
} else if (errorResponse.message == 'Network Error') {
errorMessages = 'Please check your internet connection and try again.';
} else if (errorResponse.message) {
errorMessages = errorResponse.message;
} else {
errorMessages = 'Something went wrong, please try again later.';
}
}
throw errorMessages;
});
}
}
export { API };