@@ -18,7 +18,7 @@ const makeUrl = (location: string, queryParams?: QueryParams) => {
18
18
: targetUrl
19
19
}
20
20
21
- const apiFetch = ( method : RequestInit [ 'method' ] , url : string , body ?: RequestInit [ 'body' ] , customHeaders = true ) =>
21
+ const apiFetch = < R > ( method : RequestInit [ 'method' ] , url : string , body ?: RequestInit [ 'body' ] , customHeaders = true ) =>
22
22
fetch ( url , {
23
23
method,
24
24
headers : customHeaders
@@ -33,15 +33,25 @@ const apiFetch = (method: RequestInit['method'], url: string, body?: RequestInit
33
33
. then ( response => response . status >= FIRST_HTTP_CODE && response . status <= LAST_HTTP_CODE
34
34
? Promise . reject ( response )
35
35
: response )
36
+ . then < R & { token ?: string } > ( response => response . json ( ) )
37
+ . then ( response => {
38
+ // If a token is sent back as part of any response, set it.
39
+ // This could be a first login, or a login session extension.
40
+ if ( response . token ) {
41
+ localStorage . setItem ( 'jwtToken' , response . token )
42
+ }
43
+
44
+ return response as R
45
+ } )
36
46
37
- export const apiGet = ( location : string , queryParams ?: QueryParams , customHeaders = true ) =>
38
- apiFetch ( 'GET' , makeUrl ( location , queryParams ) , undefined , customHeaders )
47
+ export const apiGet = < R > ( location : string , queryParams ?: QueryParams , customHeaders = true ) =>
48
+ apiFetch < R > ( 'GET' , makeUrl ( location , queryParams ) , undefined , customHeaders )
39
49
40
- export const apiPost = ( location : string , body ?: Record < string , unknown > ) =>
41
- apiFetch ( 'POST' , makeUrl ( location ) , JSON . stringify ( body ) )
50
+ export const apiPost = < R > ( location : string , body ?: Record < string , unknown > ) =>
51
+ apiFetch < R > ( 'POST' , makeUrl ( location ) , JSON . stringify ( body ) )
42
52
43
- export const apiPut = ( location : string , body ?: Record < string , unknown > ) =>
44
- apiFetch ( 'PUT' , makeUrl ( location ) , JSON . stringify ( body ) )
53
+ export const apiPut = < R > ( location : string , body ?: Record < string , unknown > ) =>
54
+ apiFetch < R > ( 'PUT' , makeUrl ( location ) , JSON . stringify ( body ) )
45
55
46
- export const apiDelete = ( location : string ) =>
47
- apiFetch ( 'DELETE' , makeUrl ( location ) )
56
+ export const apiDelete = < R > ( location : string ) =>
57
+ apiFetch < R > ( 'DELETE' , makeUrl ( location ) )
0 commit comments