1
- import { PUBLIC_API_URL } from '$env/static/public' ;
1
+ import { PUBLIC_API_URL , PUBLIC_JWT_REFRESH_KEY , PUBLIC_JWT_ACCESS_KEY } from '$env/static/public' ;
2
2
import type { Cookies } from '@sveltejs/kit' ;
3
- import { JWT_REFRESH_KEY , JWT_ACCESS_KEY , appendCookieHeader } from '$lib/auth' ;
3
+ import { appendCookieHeader } from '$lib/auth' ;
4
4
5
- async function _fetchAdapter (
5
+ async function _fetchApi (
6
6
relativeUrl : URL | string ,
7
7
method : string ,
8
8
body ?: string | null ,
@@ -15,19 +15,15 @@ async function _fetchAdapter(
15
15
}
16
16
17
17
async function _refreshAccessToken ( cookies : Cookies ) : Promise < string | null > {
18
- const refreshToken = cookies . get ( JWT_REFRESH_KEY ) ;
19
- const response = await _fetchAdapter (
20
- 'auth/refresh' ,
21
- 'POST' ,
22
- JSON . stringify ( { token : refreshToken } )
23
- ) ;
18
+ const refreshToken = cookies . get ( PUBLIC_JWT_REFRESH_KEY ) ;
19
+ const response = await _fetchApi ( 'auth/refresh' , 'POST' , JSON . stringify ( { token : refreshToken } ) ) ;
24
20
25
21
if ( ! response . ok ) {
26
22
return null ;
27
23
}
28
24
29
25
const json = await response . json ( ) ;
30
- return json [ JWT_ACCESS_KEY ] ;
26
+ return json [ PUBLIC_JWT_ACCESS_KEY ] ;
31
27
}
32
28
33
29
export async function fetchWithAuth (
@@ -37,16 +33,16 @@ export async function fetchWithAuth(
37
33
headers ?: HeadersInit ,
38
34
body ?: string | null
39
35
) : Promise < Response > {
40
- const jwt = cookies . get ( JWT_ACCESS_KEY ) ;
36
+ const jwt = cookies . get ( PUBLIC_JWT_ACCESS_KEY ) ;
41
37
42
38
if ( ! jwt ) {
43
- return _fetchAdapter ( relativeUrl , method , body , new Headers ( headers ) ) ;
39
+ return _fetchApi ( relativeUrl , method , body , new Headers ( headers ) ) ;
44
40
}
45
41
46
42
const authHeaders = new Headers ( headers ) ;
47
43
authHeaders . append ( 'Authorization' , `Bearer ${ jwt } ` ) ;
48
44
49
- const response = await _fetchAdapter ( relativeUrl , method , body , authHeaders ) ;
45
+ const response = await _fetchApi ( relativeUrl , method , body , authHeaders ) ;
50
46
51
47
const unauthorized = response . status >= 401 && response . status <= 403 ;
52
48
if ( unauthorized ) {
@@ -58,11 +54,11 @@ export async function fetchWithAuth(
58
54
const newAuthHeaders = new Headers ( headers ) ;
59
55
newAuthHeaders . set ( 'Authorization' , `Bearer ${ accessToken } ` ) ;
60
56
61
- const newResponse = await _fetchAdapter ( relativeUrl , method , body , newAuthHeaders ) ;
57
+ const newResponse = await _fetchApi ( relativeUrl , method , body , newAuthHeaders ) ;
62
58
63
59
if ( newResponse . ok ) {
64
60
const newResponseWithCookies = new Response ( newResponse . clone ( ) . body , newResponse ) ;
65
- appendCookieHeader ( newResponseWithCookies , JWT_ACCESS_KEY , accessToken ) ;
61
+ appendCookieHeader ( newResponseWithCookies , PUBLIC_JWT_ACCESS_KEY , accessToken ) ;
66
62
return newResponseWithCookies ;
67
63
}
68
64
}
0 commit comments