-
-
Save AitorAlejandro/e1a5678bc15b6669b63bee08cb367f54 to your computer and use it in GitHub Desktop.
Axios API Request with TypeScript
This file contains hidden or 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
import axios, { AxiosResponse } from 'axios'; | |
import { PostType } from '../models/post.interface'; | |
const instance = axios.create({ | |
baseURL: 'http://jsonplaceholder.typicode.com/', | |
timeout: 15000, | |
}); | |
const responseBody = (response: AxiosResponse) => response.data; | |
const requests = { | |
get: (url: string) => instance.get(url).then(responseBody), | |
post: (url: string, body: {}) => instance.post(url, body).then(responseBody), | |
put: (url: string, body: {}) => instance.put(url, body).then(responseBody), | |
delete: (url: string) => instance.delete(url).then(responseBody), | |
}; | |
export const Post = { | |
getPosts: (): Promise<PostType[]> => requests.get('posts'), | |
getAPost: (id: number): Promise<PostType> => requests.get(`posts/${id}`), | |
createPost: (post: PostType): Promise<PostType> => | |
requests.post('posts', post), | |
updatePost: (post: PostType, id: number): Promise<PostType> => | |
requests.put(`posts/${id}`, post), | |
deletePost: (id: number): Promise<void> => requests.delete(`posts/${id}`), | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment