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

posts.ts

46 lines1.1 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​
12const queryURL = 'https://jsonplaceholder.typicode.com'
13​
14const fetchPosts = async () => {
15 console.info('Fetching posts...')
16 await new Promise((r) => setTimeout(r, 500))
17 return axios
18 .get<Array<PostType>>(`${queryURL}/posts`)
19 .then((r) => r.data.slice(0, 10))
21​
22const fetchPost = async (postId: string) => {
23 console.info(`Fetching post with id ${postId}...`)
24 await new Promise((r) => setTimeout(r, 500))
25 const post = await axios
26 .get<PostType>(`${queryURL}/posts/${postId}`)
27 .then((r) => r.data)
28​
29 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
30 if (!post) {
31 throw new NotFoundError(`Post with id "${postId}" not found!`)
32 }
33​
34 return post
36​
37export const postQueryOptions = (postId: string) =>
38 queryOptions({
39 queryKey: ['posts', { postId }],
40 queryFn: () => fetchPost(postId),
41 })
42​
43export const postsQueryOptions = queryOptions({
44 queryKey: ['posts'],
45 queryFn: () => fetchPosts(),
46})