11import { getAuth , onAuthStateChanged } from "firebase/auth" ;
22import type { User } from "firebase/auth" ;
33import type { IDToken } from "../../common/types" ;
4+ import { app } from "../config" ;
45
56export class ErrUnauthorized extends Error { }
67
7- export async function getIdToken ( ) : Promise < IDToken > {
8- const auth = getAuth ( ) ;
9- const user = await new Promise < User > ( ( resolve ) => {
10- const unsubscribe = onAuthStateChanged ( auth , ( user : User | null ) => {
11- if ( user != null ) {
12- resolve ( user ) ;
13- unsubscribe ( ) ;
14- } else {
15- console . error ( "getIdToken: user is null" ) ;
16- }
17- } ) ;
18- } ) ;
19-
20- if ( user == null ) {
21- throw new Error (
22- "Client Error: firebase/auth/lib.ts: current user not found" ,
23- ) ;
8+ let user : User ;
9+ let token : string ;
10+
11+ const auth = getAuth ( app ) ;
12+ onAuthStateChanged ( auth , async ( u : User | null ) => {
13+ if ( u != null ) {
14+ user = u ;
15+ token = await user . getIdToken ( ) ;
2416 }
17+ } ) ;
18+
19+ async function refreshToken ( ) {
20+ token = await user . getIdToken ( true ) ;
21+ }
2522
26- return await user . getIdToken ( true ) ;
23+ export async function getIdToken ( ) : Promise < IDToken > {
24+ if ( token ) return token ;
25+ await refreshToken ( ) ;
26+ return token ;
2727}
2828
2929type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" ;
@@ -48,9 +48,11 @@ export async function credFetch(
4848 } ;
4949 }
5050
51- const res = await fetch ( `${ path } ?token=${ idToken } ` , init ) ;
51+ let res = await fetch ( `${ path } ?token=${ idToken } ` , init ) ;
52+ if ( res . status === 401 ) {
53+ await refreshToken ( ) ;
54+ res = await fetch ( `${ path } ?token=${ idToken } ` ) ;
55+ }
5256
53- // if (res.status === 401) throw new ErrUnauthorized();
54- // if (!res.ok) throw new Error("response was not ok");
5557 return res ;
5658}
0 commit comments