Skip to content

Instantly share code, notes, and snippets.

@eotkd4791
Last active May 20, 2022 01:20
Show Gist options
  • Save eotkd4791/9085c622ba39516916d92e2726a4a102 to your computer and use it in GitHub Desktop.
Save eotkd4791/9085c622ba39516916d92e2726a4a102 to your computer and use it in GitHub Desktop.
fetch API with TypeScript
interface HttpRequestOptions {
withCredentials: boolean;
}
class HttpRequest {
get(url: string, options: HttpRequestOptions = { withCredentials: false }) {
return fetch(url, {
method: 'get',
credentials: options.withCredentials ? 'include' : 'omit',
});
}
post<T>(url: string, body: T, options: HttpRequestOptions = { withCredentials: false }) {
return fetch(url, {
method: 'post',
credentials: options.withCredentials ? 'include' : 'omit',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
});
}
put<T>(url: string, body: T, options: HttpRequestOptions = { withCredentials: true }) {
return fetch(url, {
method: 'put',
credentials: options.withCredentials ? 'include' : 'omit',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
});
}
patch<T>(url: string, body: T, options: HttpRequestOptions = { withCredentials: true }) {
return fetch(url, {
method: 'patch',
credentials: options.withCredentials ? 'include' : 'omit',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
});
}
delete(url: string, options: HttpRequestOptions = { withCredentials: true }) {
return fetch(url, {
method: 'delete',
credentials: options.withCredentials ? 'include' : 'omit',
headers: {
'Content-Type': 'application/json',
}
});
}
}
const httpRequest = new HttpRequest();
const BASE_URL = 'https://jsonplaceholder.typicode.com';
// Get
httpRequest.get(`${BASE_URL}/todos/1`)
.then(res => res.json())
.then(console.log);
// Post
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
httpRequest.post<Post>(`${BASE_URL}/posts`, {
userId: 1,
id: 2,
title: 'Hello, WireBarley FE Team',
body: `Let's go !!`
})
.then(res => console.log(res.status)); // 201 CREATED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment