/
auth.store.ts
71 lines (70 loc) · 2.56 KB
/
auth.store.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
60
61
62
63
64
65
66
67
68
69
70
71
import { signalStore, withState, withMethods, patchState } from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { AuthState, authInitialState, initialUserValue } from './auth.model';
import { inject } from '@angular/core';
import { AuthService } from './services/auth.service';
import { exhaustMap, pipe, switchMap, tap } from 'rxjs';
import { concatLatestFrom, tapResponse } from '@ngrx/operators';
import { Store } from '@ngrx/store';
import { formsActions, ngrxFormsQuery } from '@realworld/core/forms';
import { LocalStorageJwtService } from './services/local-storage-jwt.service';
import { Router } from '@angular/router';
export const AuthStore = signalStore(
{ providedIn: 'root' },
withState<AuthState>(authInitialState),
withMethods(
(
store,
reduxStore = inject(Store),
authService = inject(AuthService),
localStorageService = inject(LocalStorageJwtService),
router = inject(Router),
) => ({
getUser: rxMethod<void>(
pipe(
switchMap(() => authService.user()),
tap(({ user }) => patchState(store, { user, loggedIn: true })),
),
),
login: rxMethod<void>(
pipe(
concatLatestFrom(() => reduxStore.select(ngrxFormsQuery.selectData)),
exhaustMap(([, data]) =>
authService.login(data).pipe(
tapResponse({
next: ({ user }) => {
patchState(store, { user, loggedIn: true });
localStorageService.setItem(user.token);
router.navigateByUrl('/');
},
error: ({ error }) => reduxStore.dispatch(formsActions.setErrors({ errors: error.errors })),
}),
),
),
),
),
register: rxMethod<void>(
pipe(
concatLatestFrom(() => reduxStore.select(ngrxFormsQuery.selectData)),
exhaustMap(([, data]) =>
authService.register(data).pipe(
tapResponse({
next: ({ user }) => {
patchState(store, { user, loggedIn: true });
localStorageService.setItem(user.token);
router.navigateByUrl('/');
},
error: ({ error }) => reduxStore.dispatch(formsActions.setErrors({ errors: error.errors })),
}),
),
),
),
),
logout: () => {
patchState(store, { user: initialUserValue, loggedIn: false });
localStorageService.removeItem();
router.navigateByUrl('login');
},
}),
),
);