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

api.ts

110 lines3.0 KB

1import type { Todo, Todos } from './types'
2import {
3 errorRate,
4 queryTimeMax,
5 queryTimeMin,
6 ref,
7 snapshot,
8} from '$lib/stores.svelte'
9​
10let initialId = 0
11const initialList: Todos = [
12 'apple',
13 'banana',
14 'pineapple',
15 'grapefruit',
16 'dragonfruit',
17 'grapes',
18].map((d) => ({ id: initialId++, name: d, notes: 'These are some notes' }))
19​
20const list = ref(initialList)
21const nextId = ref(initialId)
22​
23export const todosAPI = {
24 getTodos: async ({ filter }: { filter: string }): Promise<Todos> => {
25 return new Promise((resolve, reject) => {
26 setTimeout(
27 () => {
28 if (Math.random() < errorRate.value) {
29 return reject(
30 new Error(JSON.stringify({ fetchTodos: { filter } }, null, 2)),
31 )
32 }
33 resolve(list.value.filter((d) => d.name.includes(filter)))
34 },
35 queryTimeMin.value +
36 Math.random() * (queryTimeMax.value - queryTimeMin.value),
37 )
38 })
39 },
40 getTodo: async ({ id }: { id: number }): Promise<Todo> => {
41 return new Promise((resolve, reject) => {
42 setTimeout(
43 () => {
44 if (Math.random() < errorRate.value) {
45 return reject(
46 new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2)),
47 )
48 }
49 const todo = snapshot(list.value.find((d) => d.id === id))
50 if (!todo) {
51 return reject(
52 new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2)),
53 )
54 }
55 resolve(todo)
56 },
57 queryTimeMin.value +
58 Math.random() * (queryTimeMax.value - queryTimeMin.value),
59 )
60 })
61 },
62 createTodo: async ({ name, notes }: Omit<Todo, 'id'>): Promise<Todo> => {
63 return new Promise((resolve, reject) => {
64 setTimeout(
65 () => {
66 if (Math.random() < errorRate.value) {
67 return reject(
68 new Error(
69 JSON.stringify(
70 { postTodo: { name: snapshot(name), notes } },
71 null,
72 2,
73 ),
74 ),
75 )
76 }
77 const todo = { name, notes, id: nextId.value }
78 nextId.value = nextId.value + 1
79 list.value.push(todo)
80 resolve(todo)
81 },
82 queryTimeMin.value +
83 Math.random() * (queryTimeMax.value - queryTimeMin.value),
84 )
85 })
86 },
87 updateTodo: (todo: Todo): Promise<Todo> => {
88 console.info('patchTodo', todo)
89 return new Promise((resolve, reject) => {
90 setTimeout(
91 () => {
92 if (Math.random() < errorRate.value) {
93 return reject(
94 new Error(JSON.stringify({ patchTodo: todo }, null, 2)),
95 )
96 }
97 list.value = list.value.map((d) => {
98 if (d.id === todo.id) {
99 return snapshot(todo)
100 }
101 return d
102 })
103 resolve(todo)
104 },
105 queryTimeMin.value +
106 Math.random() * (queryTimeMax.value - queryTimeMin.value),
107 )
108 })
109 },