Last active
February 17, 2020 11:51
-
-
Save Temirtator/9cf86419c49c9cc5230560a534e4f148 to your computer and use it in GitHub Desktop.
Refresh token realization
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
const GET = async(navigation: any, url: string, sec: boolean = true, baseURL: boolean = true) => { | |
const headers = await getHeaders(sec); | |
const params = { method: "GET", headers }; | |
const requestURL = baseURL ? `${BASE_URL}${url}` : url; | |
const result = await makeRequest(requestURL, params, navigation); | |
return result; | |
}; | |
const makeRequest = async(url: string, params: any, navigation: any) => { | |
try { | |
const resp: any = await timeout(1000 * 30, fetch(url, params)); | |
const isNotRefresh = url.indexOf("token/refresh") < 0; | |
if (resp.status === 401) { // unauthorized | |
let refreshResp; | |
if (isNotRefresh) refreshResp = await refresh(navigation); | |
if (refreshResp === true && isNotRefresh) { // rt is not expired | |
params.headers = await getHeaders(true); // update request params | |
const prevRequest: any = await timeout(1000 * 30, fetch(url, params)); // getting response | |
if (checkResponse(prevRequest)) return prevRequest.json(); // setting response | |
return prevRequest; | |
} else { // rt is expired => clearing old datas | |
await secure.clear(); | |
await firebase.messaging().deleteToken(); | |
await navigation.navigate(`${ScreenPath.auth}`); | |
return null; | |
} | |
} else if (resp.status === 404) { // not found | |
return null; | |
} | |
if (checkResponse(resp)) return resp.json(); | |
return resp; | |
} catch (err) { | |
showError(err); | |
return null; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hope it helps