Created
October 10, 2022 15:46
-
-
Save robsonribeiros/e61897a1e466a546ea1eb0d81341d18d to your computer and use it in GitHub Desktop.
apiclient
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, { AxiosError } from "axios"; | |
import { parseCookies, setCookie } from "nookies"; | |
type FailureRequest = { | |
onSuccess: (token: string) => void; | |
onFailure: (error: AxiosError) => void; | |
} | |
let isRefreshingToken = false; | |
let failedRequestsQueue: FailureRequest[] = []; | |
export function setupAPIClient(ctx = undefined) { | |
let cookies = parseCookies(ctx); | |
const api = axios.create({ | |
baseURL: process.env.NEXT_PUBLIC_API_URL, | |
headers: { | |
Authorization: `Bearer ${cookies["joggahub:token"]}` | |
} | |
}) | |
api.interceptors.response.use(response => { | |
return response; | |
}, (error: AxiosError<any>) => { | |
if (error.response?.status === 401) { | |
if (error.response?.data?.code === "token.expired") { | |
debugger | |
console.log("ERROR RESPONSE =>", error.response?.data) | |
cookies = parseCookies(ctx); | |
const { 'joggahub:refresh_token': refresh_token, 'joggahub:token': token } = cookies; | |
const originalConfig = error.config; | |
if (!isRefreshingToken) { | |
isRefreshingToken = true; | |
api.post('auth/refresh', { refresh_token: refresh_token }, { | |
headers: { "Authorization": `Bearer ${refresh_token}` } | |
}) | |
.then(response => { | |
const { token, tokenMaxAge, refresh_token, refreshTokenMaxAge } = response?.data; | |
setCookie(ctx, "joggahub:token", token, { | |
maxAge: tokenMaxAge, | |
secure: process.env.NODE_ENV === "production" || false, | |
httpOnly: process.env.NODE_ENV === "production" || false, | |
path: '/', | |
}) | |
setCookie(ctx, "joggahub:refresh_token", refresh_token, { | |
maxAge: refreshTokenMaxAge, | |
secure: process.env.NODE_ENV === "production" || false, | |
httpOnly: process.env.NODE_ENV === "production" || false, | |
path: '/', | |
}) | |
api.defaults.headers.common['Authorization'] = `Bearer ${token}`; | |
failedRequestsQueue.forEach(request => request.onSuccess(token)); | |
failedRequestsQueue = []; | |
}) | |
.catch(error => { | |
failedRequestsQueue.forEach(request => request.onFailure(error)); | |
failedRequestsQueue = []; | |
if (typeof window !== 'undefined') { | |
// Logout(); | |
alert("Logout") | |
} | |
}) | |
.finally(() => { | |
isRefreshingToken = false; | |
}); | |
} | |
return new Promise((resolve, reject) => { | |
failedRequestsQueue.push({ | |
onSuccess: (token: string) => { | |
originalConfig.headers!.Authorization = `Bearer ${token}`; | |
resolve(api(originalConfig)); | |
}, | |
onFailure: (error: AxiosError) => { | |
reject(error); | |
} | |
}) | |
}) | |
} else { | |
console.log() | |
if (typeof window !== 'undefined') { | |
// Logout(); | |
alert("logout") | |
} | |
} | |
} | |
return Promise.reject(error); | |
}); | |
return api; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment