Created
October 10, 2023 05:23
-
-
Save philoniare/1adc501ad4f57f333b5e0b89a68545e6 to your computer and use it in GitHub Desktop.
Code Sample
This file contains 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
// Decorator to cache function results | |
function Cache(duration: number) { | |
const cache = new Map<string, { expiry: number, value: any }>(); | |
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { | |
const originalMethod = descriptor.value; | |
descriptor.value = async function (...args: any[]) { | |
const key = JSON.stringify(args); | |
const cached = cache.get(key); | |
if (cached && cached.expiry > Date.now()) { | |
return cached.value; | |
} | |
const result = await originalMethod.apply(this, args); | |
cache.set(key, { expiry: Date.now() + duration, value: result }); | |
return result; | |
}; | |
}; | |
} | |
class APIClient<T> { | |
private baseUrl: string; | |
constructor(baseUrl: string) { | |
this.baseUrl = baseUrl; | |
} | |
@Cache(60000) // Cache for 1 minute | |
async fetchResource(endpoint: string): Promise<T> { | |
const response = await fetch(`${this.baseUrl}/${endpoint}`); | |
if (response.ok) { | |
return response.json(); | |
} else { | |
throw new Error(`Failed to fetch ${endpoint}`); | |
} | |
} | |
} | |
// Usage | |
const client = new APIClient<{ name: string }>("https://api.example.com"); | |
client.fetchResource("resource").then((data) => console.log(data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment