forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.service.ts
59 lines (54 loc) · 1.63 KB
/
tasks.service.ts
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
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 {
readonly #queryClient = inject(QueryClient) // Manages query state and caching
readonly #http = inject(HttpClient) // Handles HTTP requests
/**
* Fetches all tasks from the API.
* Returns an observable containing an array of task strings.
*/
allTasks = (intervalMs: number) =>
queryOptions({
queryKey: ['tasks'],
queryFn: () => {
return lastValueFrom(this.#http.get<Array<string>>('/api/tasks'))
},
refetchInterval: intervalMs,
})
/**
* 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: string) =>
lastValueFrom(this.#http.post('/api/tasks', task)),
mutationKey: ['tasks'],
onSuccess: () => {
return this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
},
})
}
/**
* Creates a mutation for clearing all tasks.
* On success, invalidates and refetches the "tasks" query cache to ensure consistency.
*/
clearAllTasks() {
return mutationOptions({
mutationFn: () => lastValueFrom(this.#http.delete('/api/tasks')),
mutationKey: ['clearTasks'],
onSuccess: () => {
return this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
},
})
}
}