Skip to content

Commit

Permalink
[mobile]feat: searh new token
Browse files Browse the repository at this point in the history
  • Loading branch information
mgckaled committed Jan 24, 2023
1 parent d362adc commit 8e47c45
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 6 deletions.
Binary file modified api/src/database/database.db
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
56 changes: 50 additions & 6 deletions mobile/src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import axios, { AxiosInstance } from 'axios'

import { AppError } from '@utils/AppError'

import { storageAuthTokenGet } from '@storage/storageAuthToken'
import {
storageAuthTokenGet,
storageAuthTokenSave
} from '@storage/storageAuthToken'

type SignOut = () => void

Expand All @@ -11,17 +14,34 @@ type PromiseType = {
reject: (reason: unknown) => void
}

type ProccessQueueParams = {
error: Error | null
token: string | null
}

type APIInstanceProps = AxiosInstance & {
registerInterceptTokenManager: (signOut: SignOut) => () => void
}

let isRefreshing = false
let failedQueue: Array<PromiseType> = []

const api = axios.create({
baseURL: 'http:https://192.168.15.7:3333'
baseURL: 'http:https://192.168.15.3:3333'
}) as APIInstanceProps

let failedQueue: Array<PromiseType> = []
let isRefreshing = false

const proccessQueue = ({ error, token = null }: ProccessQueueParams): void => {
failedQueue.forEach(request => {
if (error) {
request.reject(error)
} else {
request.resolve(token)
}
})

failedQueue = []
}

api.registerInterceptTokenManager = singOut => {
const interceptTokenManager = api.interceptors.response.use(
response => response,
Expand All @@ -45,7 +65,7 @@ api.registerInterceptTokenManager = singOut => {
failedQueue.push({ resolve, reject })
})
.then(token => {
originalRequest.headers.Authorization = `Bearer ${token}`
originalRequest.headers['Authorization'] = `Bearer ${token}`
return axios(originalRequest)
})
.catch(error => {
Expand All @@ -54,6 +74,30 @@ api.registerInterceptTokenManager = singOut => {
}

isRefreshing = true

return new Promise(async (resolve, reject) => {
try {
const { data } = await api.post('/sessions/refresh-token', {
token: oldToken
})
await storageAuthTokenSave(data.token)

api.defaults.headers.common[
'Authorization'
] = `Bearer ${data.token}`
originalRequest.headers['Authorization'] = `Bearer ${data.token}`

proccessQueue({ error: null, token: data.token })

resolve(originalRequest)
} catch (error: any) {
proccessQueue({ error, token: null })
singOut()
reject(error)
} finally {
isRefreshing = false
}
})
}

singOut()
Expand Down

0 comments on commit 8e47c45

Please sign in to comment.