Skip to content

Instantly share code, notes, and snippets.

@Temirtator
Last active February 17, 2020 11:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Temirtator/9cf86419c49c9cc5230560a534e4f148 to your computer and use it in GitHub Desktop.
Save Temirtator/9cf86419c49c9cc5230560a534e4f148 to your computer and use it in GitHub Desktop.
Refresh token realization
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;
}
};
@Temirtator
Copy link
Author

Hope it helps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment