Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

posts.tsx

41 lines977 Bytes

1import axios from 'redaxios'
2​
3export function sleep(ms: number) {
4 return new Promise((r) => setTimeout(r, ms))
5}
6​
7export type PostType = {
8 id: string
9 title: string
10 body: string
12​
13let queryURL = 'https://jsonplaceholder.typicode.com'
14​
15if (import.meta.env.VITE_NODE_ENV === 'test') {
16 queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}`
18​
19export class PostNotFoundError extends Error {}
20​
21export const fetchPost = async (postId: string) => {
22 console.info(`Fetching post with id ${postId}...`)
23 const post = await axios
24 .get<PostType>(`${queryURL}/posts/${postId}`)
25 .then((r) => r.data)
26 .catch((err) => {
27 if (err.status === 404) {
28 throw new PostNotFoundError(`Post with id "${postId}" not found!`)
29 }
30 throw err
31 })
32​
33 return post
35​
36export const fetchPosts = async () => {
37 console.info('Fetching posts...')
38 return axios
39 .get<Array<PostType>>(`${queryURL}/posts`)
40 .then((r) => r.data.slice(0, 10))