Open History to see the last commit
1import { notFound } from '@tanstack/react-router'
2import { createServerFn } from '@tanstack/react-start'
3import axios from 'redaxios'
4β
5export type PostType = {
6 id: string
7 title: string
8 body: string
9}
10β
11let queryURL = 'https://jsonplaceholder.typicode.com'
12β
13if (import.meta.env.VITE_NODE_ENV === 'test') {
14 queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}`
15}
16β
17export const fetchPost = createServerFn({ method: 'GET' })
18 .inputValidator((postId: string) => postId)
19 .handler(async ({ data: postId }) => {
20 console.info(`Fetching post with id ${postId}...`)
21 const post = await axios
22 .get<PostType>(`${queryURL}/posts/${postId}`)
23 .then((r) => r.data)
24 .catch((err) => {
25 console.error(err)
26 if (err.status === 404) {
27 throw notFound()
28 }
29 throw err
30 })
31β
32 return post
33 })
34β
35export const fetchPosts = createServerFn({ method: 'GET' }).handler(
36 async () => {
37 console.info('Fetching posts...')
38 return axios
39 .get<Array<PostType>>(`${queryURL}/posts`)
40 .then((r) => r.data.slice(0, 10))
41 },
42)