Created
July 26, 2019 14:27
-
-
Save SmolinPavel/3b61fdcd3ad924c85a165406ff0f4b8c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios'; | |
import { LANGUAGE_NAME, REFRESH_TOKEN_IN_STORE, TOKEN_NAME_IN_STORE } from '../constants/api'; | |
import { getBrowserLang, setTokens } from './GlobalHelper'; | |
import { logoutDispatch } from './StoreHelper'; | |
import LocalStorageHelper from './LocalStorageHelper'; | |
import { BACKEND_ROUTES } from '../constants/routes'; | |
export const API_REQUEST_AUTH_USER_LOGIN_URL = '/users/login'; | |
export const API_REQUEST_AUTH_USER_LOGIN_SOCIAL_URL = '/login/social'; | |
export const API_REQUEST_AUTH_USER_REGISTER_URL = '/users/register'; | |
export const API_LOAD_RESOURCES_URL = '/users/current/user'; | |
export const API_REQUEST_PLAYER_ALL_URL = '/profile/all'; | |
export const API_REQUEST_CURRENT_PLAYER_URL = '/profile'; | |
const axiosClient = axios.create({ | |
baseURL: '/api/1.0', | |
}); | |
class ApiHelper { | |
static getHeaders(authToken, contentType = 'application/json') { | |
return { | |
'Content-Type': contentType, | |
Authorization: ApiHelper.getTokenHeader(authToken), | |
language: ApiHelper.getLanguage(), | |
}; | |
} | |
static post(url, body, contentTypeParam, token, isStringify) { | |
const authToken = token || ApiHelper.getAuthToken(); | |
const contentType = contentTypeParam || 'application/json'; | |
const finalBody = isStringify ? JSON.stringify(body) : body; | |
const headers = ApiHelper.getHeaders(authToken, contentType); | |
return axiosClient.post(url, finalBody, { | |
headers, | |
}); | |
} | |
static put(url, body, contentTypeParam, token, isStringify, withoutAuth, onProgress) { | |
const authToken = token || ApiHelper.getAuthToken(); | |
const contentType = contentTypeParam || 'application/json'; | |
const finalBody = isStringify ? JSON.stringify(body) : body; | |
const headers = { | |
'Content-Type': contentType, | |
language: ApiHelper.getLanguage(), | |
}; | |
if (!withoutAuth) { | |
headers.Authorization = ApiHelper.getTokenHeader(authToken); | |
} | |
return axiosClient.put(url, finalBody, { | |
headers, | |
onUploadProgress: onProgress, | |
}); | |
} | |
static patch(url, body, contentTypeParam, token, isStringify = true) { | |
const authToken = token || ApiHelper.getAuthToken(); | |
const contentType = contentTypeParam || 'application/json'; | |
const finalBody = isStringify ? JSON.stringify(body) : body; | |
const headers = ApiHelper.getHeaders(authToken, contentType); | |
return axiosClient.patch(url, finalBody, { headers }); | |
} | |
static get(url, config, token) { | |
const authToken = token || ApiHelper.getAuthToken(); | |
const headers = ApiHelper.getHeaders(authToken); | |
return axiosClient.get(url, { | |
...config, | |
headers, | |
}); | |
} | |
static delete(url, token) { | |
const authToken = token || ApiHelper.getAuthToken(); | |
const headers = ApiHelper.getHeaders(authToken); | |
return axiosClient.delete(url, { headers }); | |
} | |
static async doRequest(url, type, ...rest) { | |
try { | |
const response = await ApiHelper[type](url, ...rest); | |
let data = {}; | |
if (response.body !== null) { | |
// todo how to resolve it. | |
// eslint-disable-next-line prefer-destructuring | |
data = response.data; | |
} | |
return Promise.resolve(data); | |
} catch (error) { | |
return Promise.reject(error); | |
} | |
} | |
static getTokenHeader(authToken) { | |
return `Bearer ${authToken}`; | |
} | |
static getLanguage() { | |
return localStorage.getItem(LANGUAGE_NAME) || getBrowserLang(); | |
} | |
static getAuthToken() { | |
return localStorage.getItem(TOKEN_NAME_IN_STORE); | |
} | |
static isAuthenticated = () => ApiHelper.getAuthToken() != null; | |
static isObject = data => (typeof data === 'object' && data !== null) || typeof data === 'function'; | |
static getErrors(data, defaultError = 'Undefined error') { | |
const type = typeof data; | |
switch (type) { | |
case 'string': | |
return [data]; | |
case 'object': | |
if ({}.hasOwnProperty.call(data, 'error')) { | |
return [data.error]; | |
} | |
if ({}.hasOwnProperty.call(data, 'message')) { | |
return [data.message]; | |
} | |
if ({}.hasOwnProperty.call(data, 'errors')) { | |
return data.errors; | |
} | |
if ({}.hasOwnProperty.call(data, 'detail')) { | |
return [data.detail]; | |
} | |
if ({}.hasOwnProperty.call(data, 'data')) { | |
return data.data; | |
} | |
return Object.keys(data).map(key => `${key}: ${data[key]}`); | |
default: | |
return defaultError; | |
} | |
} | |
} | |
axiosClient.interceptors.response.use( | |
response => { | |
if (response.status === 204) { | |
return Promise.resolve(response); | |
} | |
return response; | |
}, | |
async error => { | |
const { response, config } = error; | |
const refreshTokenStore = LocalStorageHelper.getItem(REFRESH_TOKEN_IN_STORE); | |
if (response.status === 403 || config.retry) { | |
logoutDispatch(); | |
} | |
if (!refreshTokenStore || response.status !== 401 || config.retry) { | |
return Promise.reject(ApiHelper.getErrors(response)); | |
} | |
const { | |
data: { accessToken, refreshToken }, | |
} = await ApiHelper.post(BACKEND_ROUTES.REFRESH_TOKEN, { | |
refreshToken: refreshTokenStore, | |
}); | |
setTokens(accessToken, refreshToken); | |
const headers = ApiHelper.getHeaders(accessToken); | |
const newRequest = { | |
...config, | |
baseURL: '', | |
headers, | |
retry: true, | |
}; | |
return axiosClient(newRequest); | |
} | |
); | |
export default ApiHelper; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment