Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rxState implementation #1

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,571 changes: 1,271 additions & 300 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
"@angular/platform-browser": "^17.0.0-rc.0",
"@angular/platform-browser-dynamic": "^17.0.0-rc.0",
"@angular/router": "^17.0.0-rc.0",
"@rx-angular/state": "^16.3.0",
"firebase": "^10.4.0",
"ngxtension": "^0.14.1",
"rxfire": "^6.0.5",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
Expand Down
3 changes: 1 addition & 2 deletions src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { RouterOutlet } from '@angular/router';
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet],
template: ` <router-outlet></router-outlet> `,
styles: [],
template: ` <router-outlet /> `,
})
export class AppComponent {}
6 changes: 2 additions & 4 deletions src/app/home/home.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ describe('HomeComponent', () => {
{
provide: MessageService,
useValue: {
add$: {
next: jest.fn(),
},
add: () => {},
messages: jest.fn().mockReturnValue(mockMessages),
},
},
Expand Down Expand Up @@ -66,7 +64,7 @@ describe('HomeComponent', () => {
const testValue = 'hello';
messageInput.triggerEventHandler('send', testValue);

expect(messageService.add$.next).toHaveBeenCalledWith(testValue);
expect(messageService.actions.add).toHaveBeenCalledWith(testValue);
});
});
});
Expand Down
2 changes: 1 addition & 1 deletion src/app/home/home.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { Router } from '@angular/router';
[messages]="messageService.messages()"
[activeUser]="authService.user()"
/>
<app-message-input (send)="messageService.add$.next($event)" />
<app-message-input (send)="messageService.actions.add($event)" />
</div>
`,
imports: [
Expand Down
29 changes: 7 additions & 22 deletions src/app/shared/data-access/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable, computed, inject, signal } from '@angular/core';
import { Injectable, inject } from '@angular/core';
import { from, defer } from 'rxjs';
import {
User,
Expand All @@ -9,39 +9,24 @@ import {
import { authState } from 'rxfire/auth';
import { Credentials } from '../interfaces/credentials';
import { AUTH } from 'src/app/app.config';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {rxState} from "@rx-angular/state";

export type AuthUser = User | null | undefined;

interface AuthState {
user: AuthUser;
}

@Injectable({
providedIn: 'root',
})
@Injectable({providedIn: 'root'})
export class AuthService {
private auth = inject(AUTH);

// sources
private user$ = authState(this.auth);

// state
private state = signal<AuthState>({
user: undefined,
private state = rxState<AuthState>(({set, connect}) => {
set({user: null});
connect('user', authState(this.auth));
});

// selectors
user = computed(() => this.state().user);

constructor() {
this.user$.pipe(takeUntilDestroyed()).subscribe((user) =>
this.state.update((state) => ({
...state,
user,
}))
);
}
user = this.state.signal('user');

login(credentials: Credentials) {
return from(
Expand Down
2 changes: 1 addition & 1 deletion src/app/shared/data-access/message.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ xdescribe('MessageService', () => {
content: 'test',
};

service.add$.next(testMessage.content);
service.actions.add(testMessage.content);

expect(mockCollection).toHaveBeenCalledWith({} as any, 'messages');
expect(mockAddDoc).toHaveBeenCalledWith(mockCollectionReference as any, {
Expand Down
99 changes: 39 additions & 60 deletions src/app/shared/data-access/message.service.ts
Original file line number Diff line number Diff line change
@@ -1,81 +1,60 @@
import { Injectable, computed, inject, signal } from '@angular/core';
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
import { EMPTY, Observable, Subject, defer, exhaustMap, from } from 'rxjs';
import { collection, query, orderBy, limit, addDoc } from 'firebase/firestore';
import { collectionData } from 'rxfire/firestore';
import { catchError, filter, map, retry } from 'rxjs/operators';
import {inject, Injectable} from '@angular/core';
import {defer, exhaustMap, Observable, of} from 'rxjs';
import {addDoc, collection, limit, orderBy, query} from 'firebase/firestore';
import {collectionData} from 'rxfire/firestore';
import {catchError, filter, ignoreElements, map, retry} from 'rxjs/operators';

import { FIRESTORE } from 'src/app/app.config';
import { Message } from '../interfaces/message';
import { AuthService } from './auth.service';
import {FIRESTORE} from 'src/app/app.config';
import {Message} from '../interfaces/message';
import {AuthService, AuthUser} from './auth.service';
import {rxState} from "@rx-angular/state";
import {rxActions} from "@rx-angular/state/actions";
import {rxEffects} from "@rx-angular/state/effects";

interface MessageState {
authUser: AuthUser;
messages: Message[];
error: string | null;
}

@Injectable({
providedIn: 'root',
})
@Injectable({providedIn: 'root',})
export class MessageService {
private firestore = inject(FIRESTORE);
private authService = inject(AuthService);
private authUser$ = toObservable(this.authService.user);

// sources
messages$ = this.getMessages().pipe(
// restart stream when user reauthenticates
retry({
delay: () => this.authUser$.pipe(filter((user) => !!user)),
})
);
add$ = new Subject<Message['content']>();
error$ = new Subject<string>();
logout$ = this.authUser$.pipe(filter((user) => !user));
actions = rxActions<{ add: Message['content'] }>();

// state
private state = signal<MessageState>({
messages: [],
error: null,
});
state = rxState<MessageState>(({set, connect, select}) => {
set({ messages: [], error: null });
connect('authUser', this.authService.user);

// selectors
messages = computed(() => this.state().messages);
error = computed(() => this.state().error);
const authenticated$ = select('authUser').pipe(map((user) => !!user));

constructor() {
// reducers
this.messages$.pipe(takeUntilDestroyed()).subscribe((messages) =>
this.state.update((state) => ({
...state,
messages,
}))
);
connect('messages', this.getMessages().pipe(
retry({delay: () => authenticated$ }) // restart stream when user re-authenticates
));

connect('messages', authenticated$.pipe(filter(x => !x)), () => []);

this.add$
.pipe(
takeUntilDestroyed(),
exhaustMap((message) => this.addMessage(message))
connect(
'error',
this.actions.add$.pipe(
exhaustMap((message) => this.addMessage(message)),
ignoreElements(),
catchError(err => of(err))
)
.subscribe({
error: (err) => {
console.log(err);
this.error$.next('Failed to send message');
},
});
);
});

this.logout$
.pipe(takeUntilDestroyed())
.subscribe(() =>
this.state.update((state) => ({ ...state, messages: [] }))
);
effects = rxEffects(({ register }) => {
register(this.state.select('messages'), (messages) => {
console.log('messages', messages);
})
})

this.error$
.pipe(takeUntilDestroyed())
.subscribe((error) =>
this.state.update((state) => ({ ...state, error }))
);
}
// selectors
messages = this.state.signal('messages');
error = this.state.signal('error');

private getMessages() {
const messagesCollection = query(
Expand Down