Typescript Get request
Tue Oct 01 2024 12:15:15 GMT+0000 (Coordinated Universal Time)
Saved by
@kanatov
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;
content_copyCOPY
Comments