11import axios from 'axios'
22import { AuthorizationProps } from '../types/AuthorizationProps'
3+ import { StreamProps } from '../types/StreamProps'
4+ import { getItemFromStorage } from './getItemFromStorage'
35import { getTwitchAuthorization } from './getTwitchAuthorization'
4- import type { StreamProps } from '../types/StreamProps'
56
67export const getStreams = async (
78 url : string
89) : Promise < StreamProps | undefined | { error : 'login' } > => {
10+ const parsedData = getItemFromStorage ( )
911 const authorizationObject : AuthorizationProps =
10- await getTwitchAuthorization ( )
12+ parsedData . access_token &&
13+ parsedData . expires_in &&
14+ parsedData . token_type
15+ ? {
16+ access_token : parsedData . access_token ,
17+ expires_in : parsedData . expires_in ,
18+ token_type : parsedData . token_type ,
19+ }
20+ : await getTwitchAuthorization ( )
1121 let { access_token, token_type } = authorizationObject
12- if ( ! access_token || ! token_type ) return { error : 'login' }
22+ if ( ! access_token || ! token_type ) {
23+ return { error : 'login' }
24+ }
1325
1426 token_type =
1527 token_type . substring ( 0 , 1 ) . toUpperCase ( ) +
@@ -36,6 +48,23 @@ export const getStreams = async (
3648
3749 return response . data
3850 } catch ( error : any ) {
51+ if ( axios . isAxiosError ( error ) && error . response ?. status === 401 ) {
52+ console . warn ( 'Token expired, refreshing...' )
53+
54+ const retryAuth : AuthorizationProps = await getTwitchAuthorization ( )
55+ if ( retryAuth . access_token ) {
56+ const retryResponse = await axios . post (
57+ 'https://twitch-backend.vercel.app/api/streams' ,
58+ {
59+ access_token : retryAuth . access_token ,
60+ token_type : retryAuth . token_type ,
61+ url,
62+ }
63+ )
64+ return retryResponse . data
65+ }
66+ }
67+
3968 console . error (
4069 'The following error occured while fetching the current Livestreams:' ,
4170 error
0 commit comments