I'm learning TypeScript while doing my portfolio, and I wrote a class to make a fetch request to the API that holds my data.
It is working fine. I use localStorage to set a cache to avoid calling the API often as the data won't change.
I know I could improve this a lot, and haven't used many TypeScript features, so it would be great to have some pointers on how to improve this class generally, and also how to improve it by adding some more TypeScript features.
This is the class:
export interface PortfolioData {
basics: Basics;
projects?: Project[];
}
interface Cache {
portfolio: PortfolioData;
expiration: number;
}
class Portfolio {
private url = 'https://gitconnected.com/v1/portfolio/mauriciorobayo';
private cacheDurationInMilliseconds: number;
constructor(cacheDurationInMinutes: number) {
this.cacheDurationInMilliseconds = cacheDurationInMinutes * 60 * 1000;
}
private getCache(): Cache | undefined {
const data = localStorage.getItem('portfolio');
if (!data) {
return;
}
const cache = JSON.parse(data);
if (Date.now() > cache.expiration) {
return;
}
return cache;
}
private setCache(data: Cache) {
localStorage.setItem('portfolio', JSON.stringify(data));
}
async getPortfolio(): Promise<PortfolioData> {
const cache = this.getCache();
if (cache) {
return cache.portfolio;
}
const response = await fetch(this.url);
if (response.ok) {
const portfolio = await response.json();
this.setCache({
portfolio,
expiration: Date.now() + this.cacheDurationInMilliseconds,
});
return portfolio;
}
throw new Error(response.statusText);
}
}
export default Portfolio;