@@ -73,31 +73,40 @@ export class SyncService {
7373 private initDatabases ( ) {
7474 this . remoteDatabase . initRemoteDB (
7575 `${ AppSettings . DB_PROXY_PREFIX } /${ AppSettings . DB_NAME } ` ,
76- ( url , opts : any ) => {
77- if ( typeof url === "string" ) {
78- const remoteUrl =
79- AppSettings . DB_PROXY_PREFIX +
80- url . split ( AppSettings . DB_PROXY_PREFIX ) [ 1 ] ;
81- return this . sendRequest ( remoteUrl , opts ) . then ( ( initialRes ) =>
82- // retry login if request failed with unauthorized
83- initialRes . status === HttpStatusCode . Unauthorized
84- ? this . authService
85- . login ( )
86- . then ( ( ) => this . sendRequest ( remoteUrl , opts ) )
87- // return initial response if request failed again
88- . then ( ( newRes ) => ( newRes . ok ? newRes : initialRes ) )
89- . catch ( ( ) => initialRes )
90- : initialRes ,
91- ) ;
92- }
93- } ,
76+ this . fetch . bind ( this ) ,
9477 ) ;
9578 this . remoteDB = this . remoteDatabase . getPouchDB ( ) ;
9679 if ( this . database instanceof PouchDatabase ) {
9780 this . localDB = this . database . getPouchDB ( ) ;
9881 }
9982 }
10083
84+ private async fetch ( url : string , opts : any ) {
85+ // TODO: merge this with PouchDatabase.defaultFetch, which is very similar
86+
87+ if ( typeof url !== "string" ) {
88+ return ;
89+ }
90+
91+ const remoteUrl =
92+ AppSettings . DB_PROXY_PREFIX + url . split ( AppSettings . DB_PROXY_PREFIX ) [ 1 ] ;
93+ const initialRes = await this . sendRequest ( remoteUrl , opts ) ;
94+
95+ // retry login if request failed with unauthorized
96+ if ( initialRes . status === HttpStatusCode . Unauthorized ) {
97+ return (
98+ this . authService
99+ . login ( )
100+ . then ( ( ) => this . sendRequest ( remoteUrl , opts ) )
101+ // return initial response if request failed again
102+ . then ( ( newRes ) => ( newRes . ok ? newRes : initialRes ) )
103+ . catch ( ( ) => initialRes )
104+ ) ;
105+ } else {
106+ return initialRes ;
107+ }
108+ }
109+
101110 private sendRequest ( url : string , opts ) {
102111 this . authService . addAuthHeader ( opts . headers ) ;
103112 return PouchDB . fetch ( url , opts ) ;
0 commit comments