Closed debater-coder closed 1 year ago
Hi, it's been a little while. Are there any plans to remedy this or am I doing this wrong. @evert
Hi! This ticket makes perfect sense.
I think the ideal way to solve this might be to store the promise that's returned from getNewToken on 'this' until it's resolved and await it in fetch().
I'll try to get to this in the next few days
Thank you!
I'm not sure this is fixed. I have to do this to get it to behave correctly:
await fetchWrapper.activeGetStoredToken
await fetchWrapper.getToken()
Calling just fetchWrapper.getToken()
on its own appears to always get a new token.
Here's my workaround:
export const fetchWrapper = new OAuth2Fetch({
"client": oauth2Client,
"getNewToken": async function() {
// WORKAROUND: https://github.com/badgateway/oauth2-client/issues/110
if (fetchWrapper.activeGetStoredToken !== null) {
await fetchWrapper.activeGetStoredToken;
if (existsSync("token.json")) {
return JSON.parse(await fs.readFile("token.json", { "encoding": "utf8" }));
}
}
This following code fails because getStoredToken is always invoked as an async function, meaning that
fetchWrapper.fetch()
will be called beforegetStoredToken()
has even been called. See this async IIFE. By the time thefetchWrapper.fetch()
is called, the private propertyfetchWrapper.token
is still null, sogetToken()
attempts to refresh it, which fails, invokingrefreshToken()
which attempts to refresh the non-existent token, which fails invokinggetNewToken()
which also fails, finally invokingonError
, which prompts the user to log in again. When this is finished, control returns to the async IIFE, which finally sets the token to the correct value, and the next timefetchWrapper.fetch()
is invoked, it behaves correctly. I have verified this using the debugger in Chrome DevTools. It is possible to create an async constructor by returning an IIAFE from the constructor. However, this could be tricky without introducing a breaking change. Alternatively, the IIAFE could be stored in a private property which could be awaited inside of thefetchWrapper.fetch()
function, ensuring thatgetStoredToken()
has been invoked. Until a fix is released, I have a temporary workaround, but it is quite hacky, so I would appreciate a stable fix.Problematic Code
Temporary workaround