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

posts.ts

50 lines1.2 KB

1import axios from 'redaxios'
2import { queryOptions } from '@tanstack/solid-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 await new Promise((r) => setTimeout(r, 500))
21 return axios
22 .get<Array<PostType>>(`${queryURL}/posts`)
23 .then((r) => r.data.slice(0, 10))
25​
26const fetchPost = async (postId: string) => {
27 console.info(`Fetching post with id ${postId}...`)
28 await new Promise((r) => setTimeout(r, 500))
29 const post = await axios
30 .get<PostType>(`${queryURL}/posts/${postId}`)
31 .then((r) => r.data)
32​
33 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
34 if (!post) {
35 throw new NotFoundError(`Post with id "${postId}" not found!`)
36 }
37​
38 return post
40​
41export const postQueryOptions = (postId: string) =>
42 queryOptions({
43 queryKey: ['posts', { postId }],
44 queryFn: () => fetchPost(postId),
45 })
46​
47export const postsQueryOptions = queryOptions({
48 queryKey: ['posts'],
49 queryFn: () => fetchPosts(),
50})