aboutsummaryrefslogtreecommitdiff
path: root/ufund-ui/src/app/services/users.service.ts
blob: 35d080de2a122555d0eb91f9f0e50276837ca0df (plain) (blame)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {BehaviorSubject, catchError, firstValueFrom, Observable, of} from 'rxjs';
import {User, userType} from '../models/User';
import { Need } from '../models/Need';
import { CupboardService } from './cupboard.service';
import {AuthService} from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class UsersService {

    private basket = new BehaviorSubject<Need[]>([]);
    private url = "http://localhost:8080/users"

    httpOptions = () => ({
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            "jelly-api-key": this.authService.getApiKey()
        })
    });

    httpOptions2 = () => ({
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            "jelly-api-key": this.authService.getApiKey()
        }),
        responseType: "text" as "json" // don't ask me how or why this works, bc i have no clue...
        // see the relevant angular bug report https://github.com/angular/angular/issues/18586
    });

    constructor(
        private http: HttpClient,
        private cupboardService: CupboardService,
        private authService: AuthService
    ) {
        authService.getCurrentUserSubject().subscribe(() => this.refreshBasket())
    }

    async createUser(username:string, password:string) {
        await firstValueFrom(this.http.post<User>(this.url, {username: username, password: password}, this.httpOptions()))
    }

    getUser(id: string): Observable<User> {
        return this.http.get<User>(`${this.url}/${id}`, this.httpOptions())
    }

    getCount(): Observable<number> {
        return this.http.get<number>(`${this.url}/count`, this.httpOptions2())
    }

    updateUser(user: User): Observable<User> {
        console.log(`${this.url}/${user.username}`, user, this.httpOptions)
        return this.http.put<User>(`${this.url}/${user.username}`, user, this.httpOptions())
    }

    deleteUser(id: number): Observable<boolean> {
        return this.http.delete<boolean>(`${this.url}/${id}`, this.httpOptions())
    }

    refreshBasket() {
        let promiseArr = this.authService.getCurrentUser()!.basket.map(async needID => {
            return await firstValueFrom(this.cupboardService.getNeed(needID));
        })
        Promise.all(promiseArr).then(r => this.basket.next(r));
    }

    removeNeed(id: number) {
        let newArr = this.basket.getValue().filter(v => v.id != id);
        this.basket.next(newArr);
        this.authService.getCurrentUser()!.basket = newArr.map(need => need.id);
        this.updateUser(this.authService.getCurrentUser()!)
            .pipe(
                catchError((err: any, _) => {
                    console.error(err);
                    return of();
                })
            )
            .subscribe(() => {
            this.refreshBasket();
          });
    }

    getBasket() {
        return this.basket;
    }

    isManager() {
        return this.authService.getCurrentUser()?.type === userType.MANAGER
    }

    isHelper() {
        return this.authService.getCurrentUser()?.type === userType.HELPER
    }

    inBasket(basket: Need[] | null, need: Need) {
        return basket?.map(r => r.id).includes(need.id);
    }

}