casino/frontend/src/app/service/user.service.ts
Jan-Marlon Leibl 4a7c54eab8
All checks were successful
CI / Get Changed Files (pull_request) Successful in 6s
CI / eslint (pull_request) Successful in 19s
CI / test-build (pull_request) Successful in 27s
CI / prettier (pull_request) Successful in 40s
CI / Checkstyle Main (pull_request) Successful in 1m28s
style: format code for consistency and readability
2025-04-02 10:26:11 +02:00

61 lines
1.7 KiB
TypeScript

import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { KeycloakProfile } from 'keycloak-js';
import { BehaviorSubject, catchError, EMPTY, Observable, tap } from 'rxjs';
import { User } from '../model/User';
@Injectable({
providedIn: 'root',
})
export class UserService {
private http: HttpClient = inject(HttpClient);
private currentUserSubject = new BehaviorSubject<User | null>(null);
public currentUser$ = this.currentUserSubject.asObservable();
constructor() {
// Initialize with current user data
this.getCurrentUser().subscribe();
}
public getUser(id: string): Observable<User | null> {
return this.http.get<User | null>(`/backend/user/${id}`).pipe(
catchError(() => EMPTY),
tap((user) => this.currentUserSubject.next(user))
);
}
public getCurrentUser(): Observable<User | null> {
return this.http.get<User | null>('/backend/user').pipe(
catchError(() => EMPTY),
tap((user) => this.currentUserSubject.next(user))
);
}
public refreshCurrentUser(): void {
this.getCurrentUser().subscribe();
}
public createUser(id: string, username: string): Observable<User> {
return this.http
.post<User>('/backend/user', {
keycloakId: id,
username: username,
})
.pipe(tap((user) => this.currentUserSubject.next(user)));
}
public async getOrCreateUser(userProfile: KeycloakProfile) {
if (userProfile.id == null) {
return;
}
return await this.getUser(userProfile.id)
.toPromise()
.then(async (user) => {
if (user) {
return user;
}
return await this.createUser(userProfile.id ?? '', userProfile.username ?? '').toPromise();
});
}
}