Created
September 6, 2021 12:29
-
-
Save bichotll/9148e6cabcc5c529a972e612fc0a1395 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SessionToken { | |
} | |
class IDP { | |
static token | |
} | |
const IDP = { | |
token: undefined, | |
getTokenPromise: new Promise(), | |
init() { | |
this.boundStorageEventListener() | |
}, | |
boundStorageEventListener () { | |
window.addEventListener('storage', () => { | |
if (this.token !== storageToken) { | |
this.token = storageToken | |
this.getTokenPromise.resolve() | |
this.getTokenPromise = new Promise() | |
} | |
}); | |
}, | |
getStorageToken() { | |
return window.localStorage.getItem('token') | |
}, | |
checkIfStoredTokenChanged () { | |
return this.getStorageToken() !== this.token | |
}, | |
setTokenFromStorage () { | |
this.token = this.getStorageToken() | |
}, | |
onEventChanged (callback) { | |
if (this.checkIfStoredTokenChanged()) { | |
this.setTokenFromStorage() | |
callback() | |
this.unboundStorageEventListener() | |
return | |
} | |
}, | |
listenStorageEventListener(callback) { | |
this.boundStorageEventListener = window.addEventListener('storage', this.onEventChanged.bind(callback)) | |
}, | |
unboundStorageEventListener() { | |
window.addEventListener.removeEventListener(); | |
}, | |
refreshToken() { | |
if (locked) { | |
return new Promise((resolve) => { | |
// solution 1: | |
// in case the event happens before we bound the listener | |
if (this.checkIfStoredTokenChanged()) { | |
this.setTokenFromStorage() | |
resolve() | |
return | |
} | |
listenStorageEventListener(() => { | |
resolve() | |
}) | |
// ...old code | |
// window.addEventListener('storage', () => { | |
// if (this.checkIfStoredTokenChanged()) { | |
// this.setTokenFromStorage() | |
// resolve() | |
// this.unboundStorageEventListener() | |
// return | |
// } | |
// }) | |
// solution 2: | |
// setInterval(() => { | |
// const storageToken = window.localStorage.getItem('token') | |
// if (storageToken !== this.token) { | |
// this.token = storageToken | |
// resolve() | |
// } | |
// }, 500) | |
}) | |
} | |
}, | |
} | |
// eventEmitter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment