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

posts.tsx

43 lines1.0 KB

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​
13export class PostNotFoundError extends Error {}
14​
15let queryURL = 'https://jsonplaceholder.typicode.com'
16​
17if (import.meta.env.VITE_NODE_ENV === 'test') {
18 queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}`
20​
21export const fetchPost = async (postId: string) => {
22 console.info(`Fetching post with id ${postId}...`)
23 await new Promise((r) => setTimeout(r, 500))
24 const post = await axios
25 .get<PostType>(`${queryURL}/posts/${postId}`)
26 .then((r) => r.data)
27 .catch((err) => {
28 if (err.status === 404) {
29 throw new PostNotFoundError(`Post with id "${postId}" not found!`)
30 }
31 throw err
32 })
33​
34 return post
36​
37export const fetchPosts = async () => {
38 console.info('Fetching posts...')
39 await new Promise((r) => setTimeout(r, 500))
40 return axios
41 .get<Array<PostType>>(`${queryURL}/posts`)
42 .then((r) => r.data.slice(0, 10))