54 lines
1.6 KiB
TypeScript
54 lines
1.6 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { HttpClient } from '@angular/common/http';
|
|
import { BehaviorSubject, catchError, EMPTY, Observable, tap } from 'rxjs';
|
|
import { User } from '../model/User';
|
|
import { environment } from '@environments/environment';
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class UserService {
|
|
private apiUrl = `${environment.apiUrl}/api/users`;
|
|
private currentUserSubject = new BehaviorSubject<User | null>(null);
|
|
|
|
constructor(private http: HttpClient) {}
|
|
|
|
public getUserById(id: number): Observable<User> {
|
|
return this.http.get<User>(`${this.apiUrl}/${id}`);
|
|
}
|
|
|
|
public getUserByUsername(username: string): Observable<User> {
|
|
return this.http.get<User>(`${this.apiUrl}/username/${username}`);
|
|
}
|
|
|
|
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 updateLocalBalance(amount: number): void {
|
|
const currentUser = this.currentUserSubject.getValue();
|
|
if (currentUser) {
|
|
const updatedUser = {
|
|
...currentUser,
|
|
balance: currentUser.balance + amount,
|
|
};
|
|
this.currentUserSubject.next(updatedUser);
|
|
}
|
|
}
|
|
|
|
public createUser(id: string, username: string): Observable<User> {
|
|
return this.http
|
|
.post<User>('/backend/user', {
|
|
authentikId: id,
|
|
username: username,
|
|
})
|
|
.pipe(tap((user) => this.currentUserSubject.next(user)));
|
|
}
|
|
}
|