class MakeRequests { private baseURL: string; constructor(baseURL: string) { this.baseURL = baseURL; } private async makeRequest<T>(requestInfo: RequestInfo): Promise<T> { const jsonResponse: Awaited<T> = await fetch(requestInfo) .then((response: Response) => response.json()) .then((json: T) => json); return jsonResponse; } public async getPosts(): Promise<Record<string, unknown>> { const jsonResponse: Record<string, unknown> = await this.makeRequest( new Request(`${this.baseURL}posts/1`, { headers: new Headers({ "Content-Type": "application/json" }), }) ); return jsonResponse; } } const makeRequests: MakeRequests = new MakeRequests( "https://jsonplaceholder.typicode.com/" ); export default makeRequests;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter