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