Created
January 7, 2023 19:37
-
-
Save theouerd/726241ad05fc6f680b2332175c5dc79a to your computer and use it in GitHub Desktop.
simulate how to refresh token retreived from external API, based on it's expiration date to avoid invalid token error.
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
/** | |
* Make token | |
* @param {number} length Token length | |
* @param {number} expires_in Token expiration in seconds, default: 5 secs | |
* | |
* @return {Array} | |
*/ | |
const makeToken = (length, expires_in = 5) => { | |
let token = ''; | |
const characters = | |
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | |
const charactersLength = characters.length; | |
for (var i = 0; i < length; i++) { | |
token += characters.charAt(Math.floor(Math.random() * charactersLength)); | |
} | |
return [token, expires_in]; | |
}; | |
/** | |
* Utility to simulate asynchronous call | |
* @param {number} milliseconds Time to wait in ms | |
* | |
* @return {Promise} | |
*/ | |
const delay = (milliseconds) => | |
new Promise((resolve) => setTimeout(resolve, milliseconds)); | |
(async () => { | |
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
const processStartDate = Date.now(); | |
let renewTokenDate = processStartDate; | |
let [token, expires_in] = makeToken(40); | |
let tokenIsInvalid = expires_in - 1 <= (Date.now() - renewTokenDate) / 1000; | |
// let expires_in = 5; // in sec | |
await delay(1000); | |
console.log('token >', token); | |
for (const row of data) { | |
if (tokenIsInvalid && token) { | |
console.log(`token expired > ${token}`, tokenIsInvalid); | |
renewTokenDate = Date.now(); | |
[token, expires_in] = makeToken(40); | |
await delay(1000); | |
console.log('got new token', token); | |
} | |
console.info('token is valid >', !(tokenIsInvalid && token)); | |
console.log('row value >', row); | |
await delay(1000); | |
console.log('DATA FETCHED for >', row); | |
} | |
const processEndDate = Date.now(); | |
console.log('DONE in ', (processEndDate - processStartDate) / 1000, 's'); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment