To check if a token is valid, you can create a function that returns a Promise which resolves to a boolean value as shown below:
verifyTokenValidity(): Promise<boolean> {
// |
// |----- Make sure to include the return statement here
// v
return this.storage.fetch('token_expiry')
.then((expiryTime) => {
return Date.now() < expiryTime;
})
.catch((error) => {
return false;
});
}
In the provided code snippet, there are three return statements included: one within the 'then' block of the Promise, another in the 'catch' block, and finally inside the 'verifyTokenValidity()' method itself. It's crucial for the accessor method to also have a return statement.
If you want to see this implementation in action, you can experiment with it here in the TypeScript playground:
class StorageHandler {
// Mocking storage for demonstration
private storage = {
fetch: (key: string): Promise<any> => {
return Promise.resolve(Date.now() + 86400000);
}
};
verifyTokenValidity(): Promise<boolean> {
return this.storage.fetch('token_expiry')
.then((expiryTime) => {
return Date.now() < expiryTime;
})
.catch((error) => {
return false;
});
}
}
const handler = new StorageHandler();
handler.verifyTokenValidity().then((isValid) => {
console.log(isValid); // true
});