forked from angular-architects/ngrx-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo-entity-resource.store.ts
More file actions
61 lines (60 loc) · 1.99 KB
/
Copy pathtodo-entity-resource.store.ts
File metadata and controls
61 lines (60 loc) · 1.99 KB
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
import {
httpMutation,
withEntityResources,
withMutations,
} from '@angular-architects/ngrx-toolkit';
import { inject, resource } from '@angular/core';
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
import { addEntity, removeEntity, updateEntity } from '@ngrx/signals/entities';
import { firstValueFrom } from 'rxjs';
import { Todo, TodoMemoryService } from './todo-memory.service';
export const TodoEntityResourceStore = signalStore(
{ providedIn: 'root' },
withState({ baseUrl: '/api', filter: '' }),
withEntityResources((store, svc = inject(TodoMemoryService)) =>
resource({ loader: () => firstValueFrom(svc.list()), defaultValue: [] }),
),
withMethods((store) => ({
setFilter(filter: string) {
patchState(store, { filter });
},
})),
withMutations((store, svc = inject(TodoMemoryService)) => ({
addTodo: httpMutation<Todo, Todo>({
request: (todo) => ({ url: '/memory/add', method: 'POST', body: todo }),
parse: (raw) => raw as Todo,
onSuccess: async (todo) => {
await firstValueFrom(svc.add(todo));
patchState(store, addEntity(todo));
},
}),
toggleTodo: httpMutation<{ id: number; completed: boolean }, Todo>({
request: (p) => ({
url: `/memory/toggle/${p.id}`,
method: 'PATCH',
body: p,
}),
parse: (raw) => raw as Todo,
onSuccess: async (_todo, p) => {
const todo = await firstValueFrom(svc.toggle(p.id, p.completed));
if (todo) {
patchState(
store,
updateEntity<Todo>({
id: todo.id,
changes: { completed: todo.completed },
}),
);
}
},
}),
removeTodo: httpMutation<number, boolean>({
request: (id) => ({ url: `/memory/remove/${id}`, method: 'DELETE' }),
parse: () => true,
onSuccess: async (_r, id) => {
await firstValueFrom(svc.remove(id));
patchState(store, removeEntity(id));
},
}),
})),
);