@@ -2,17 +2,32 @@ import axios from "axios";
22import { getIdentityTokenEndpoint } from "../constants" ;
33import { NavigraphCancelToken } from "../lib/navigraphRequest" ;
44import { TokenResponse } from "./types" ;
5- import { AuthenticationAbortedError , Scope } from "@navigraph/app" ;
5+ import { AuthenticationAbortedError , Logger , NotInitializedError , Scope , getApp } from "@navigraph/app" ;
66import { tokenStorage } from "../internals/storage" ;
77import { setUser } from "../internals/user" ;
88import { decodeUser } from "../util" ;
99
10+ const requests = new Map < string , Promise < TokenResponse > | null > ( ) ;
11+
1012/** Requests a token using provided options and updates the credential stores with the result. Also sets the user variable. */
1113export async function requestToken ( params : Record < string , string > , cancelToken ?: NavigraphCancelToken ) {
12- return axios
14+ const app = getApp ( ) ;
15+ if ( ! app ) throw new NotInitializedError ( "Auth" ) ;
16+
17+ const key = JSON . stringify ( params ) ;
18+ const ongoingRequest = requests . get ( key ) ;
19+
20+ if ( ongoingRequest ) {
21+ Logger . debug ( "Found ongoing request with key " + key ) ;
22+ return ongoingRequest ;
23+ }
24+
25+ Logger . debug ( "No ongoing request found with key " + key ) ;
26+
27+ const requestPromise = axios
1328 . post < TokenResponse > ( getIdentityTokenEndpoint ( ) , new URLSearchParams ( params ) , {
1429 cancelToken,
15- withCredentials : params . scope ? .includes ( Scope . TILES ) ? true : undefined ,
30+ withCredentials : app . scopes . includes ( Scope . TILES ) ? true : undefined ,
1631 headers : { "Content-Type" : "application/x-www-form-urlencoded" } ,
1732 } )
1833 . then ( async ( { data } ) => {
@@ -27,5 +42,9 @@ export async function requestToken(params: Record<string, string>, cancelToken?:
2742 if ( axios . isCancel ( err ) ) throw new AuthenticationAbortedError ( ) ;
2843
2944 throw err ;
30- } ) ;
45+ } )
46+ . finally ( ( ) => requests . delete ( key ) ) ;
47+
48+ requests . set ( key , requestPromise ) ;
49+ return requestPromise ;
3150}
0 commit comments