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