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

api.ts

69 lines1.4 KB

1import type { Todo, TodosResponse } from './types'
2​
3let todos: Array<Todo> = [
4 { id: 1, title: 'Ship lit-query alpha' },
5 { id: 2, title: 'Write integration checks' },
6]
7​
8let requestCount = 0
9let nextTodoId = 3
10let failNextFetch = false
11let failNextMutation = false
12​
13const delay = (ms: number): Promise<void> =>
14 new Promise((resolve) => {
15 setTimeout(resolve, ms)
16 })
17​
18export const todosAPI = {
19 getTodos: async (): Promise<TodosResponse> => {
20 await delay(90)
21 if (failNextFetch) {
22 failNextFetch = false
23 throw new Error('Forced fetch failure (test)')
24 }
25 requestCount += 1
26​
27 return {
28 items: todos.map((todo) => ({ ...todo })),
29 requestCount,
30 source: 'server',
31 }
32 },
33 createTodo: async (title: string): Promise<Todo> => {
34 await delay(70)
35 if (failNextMutation) {
36 failNextMutation = false
37 throw new Error('Forced mutation failure (test)')
38 }
39​
40 const nextTodo: Todo = {
41 id: nextTodoId,
42 title,
43 }
44​
45 nextTodoId += 1
46 todos = [...todos, nextTodo]
47​
48 return { ...nextTodo }
49 },
51​
52export function resetTodoApi(): void {
53 todos = [
54 { id: 1, title: 'Ship lit-query alpha' },
55 { id: 2, title: 'Write integration checks' },
56 ]
57 requestCount = 0
58 nextTodoId = 3
59 failNextFetch = false
60 failNextMutation = false
62​
63export function failNextFetchRequest(): void {
64 failNextFetch = true
66​
67export function failNextMutationRequest(): void {
68 failNextMutation = true