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

posts.ts

48 lines1.1 KB

1import axios from 'redaxios'
2import { queryOptions } from '@tanstack/react-query'
3​
4export class NotFoundError extends Error {}
5​
6type PostType = {
7 id: string
8 title: string
9 body: string
11​
12let queryURL = 'https://jsonplaceholder.typicode.com'
13​
14if (import.meta.env.VITE_NODE_ENV === 'test') {
15 queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}`
17​
18const fetchPosts = async () => {
19 console.info('Fetching posts...')
20 return axios
21 .get<Array<PostType>>(`${queryURL}/posts`)
22 .then((r) => r.data.slice(0, 10))
24​
25const fetchPost = async (postId: string) => {
26 console.info(`Fetching post with id ${postId}...`)
27 const post = await axios
28 .get<PostType>(`${queryURL}/posts/${postId}`)
29 .then((r) => r.data)
30​
31 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
32 if (!post) {
33 throw new NotFoundError(`Post with id "${postId}" not found!`)
34 }
35​
36 return post
38​
39export const postQueryOptions = (postId: string) =>
40 queryOptions({
41 queryKey: ['posts', { postId }],
42 queryFn: () => fetchPost(postId),
43 })
44​
45export const postsQueryOptions = queryOptions({
46 queryKey: ['posts'],
47 queryFn: () => fetchPosts(),
48})