File size: 2,290 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { HttpClient } from '@angular/common/http'
import { Injectable, inject } from '@angular/core'
import {
  QueryClient,
  mutationOptions,
  queryOptions,
} from '@tanstack/angular-query-experimental'

import { lastValueFrom } from 'rxjs'

@Injectable({
  providedIn: 'root',
})
export class TasksService {
  #queryClient = inject(QueryClient) // Manages query state and caching
  #http = inject(HttpClient) // Handles HTTP requests

  /**
   * Fetches all tasks from the API.
   * Returns an observable containing an array of task strings.
   */
  allTasks = () =>
    queryOptions({
      queryKey: ['tasks'],
      queryFn: () => {
        return lastValueFrom(this.#http.get<Array<string>>('/api/tasks'))
      },
    })

  /**
   * Creates a mutation for adding a task.
   * On success, invalidates and refetches the "tasks" query cache to update the task list.
   */
  addTask() {
    return mutationOptions({
      mutationFn: ({
        task,
        failMutation = false,
      }: {
        task: string
        failMutation: boolean
      }) =>
        lastValueFrom(
          this.#http.post(
            `/api/tasks${failMutation ? '-wrong-url' : ''}`,
            task,
          ),
        ),
      mutationKey: ['tasks'],
      onSuccess: () => {
        this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
      },
      onMutate: async ({ task }) => {
        // Cancel any outgoing refetches
        // (so they don't overwrite our optimistic update)
        await this.#queryClient.cancelQueries({ queryKey: ['tasks'] })

        // Snapshot the previous value
        const previousTodos = this.#queryClient.getQueryData<Array<string>>([
          'tasks',
        ])

        // Optimistically update to the new value
        if (previousTodos) {
          this.#queryClient.setQueryData<Array<string>>(
            ['tasks'],
            [...previousTodos, task],
          )
        }

        return previousTodos
      },
      onError: (err, variables, context) => {
        if (context) {
          this.#queryClient.setQueryData<Array<string>>(['tasks'], context)
        }
      },
      // Always refetch after error or success:
      onSettled: () => {
        this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
      },
    })
  }
}