import { Injectable } from "@angular/core"; import { EmployeeRequestDTO, EmployeeRequestPutDTO, EmployeeResponseDTO } from "../models/mitarbeiter"; import { HttpClient } from "@angular/common/http"; import { Observable } from "rxjs"; import { SkillService } from "./skill.service"; @Injectable({ providedIn: 'root' }) export class EmployeeService { constructor(private http: HttpClient) { } responseToRequestDto(employee: EmployeeResponseDTO): EmployeeRequestDTO { return { firstName: employee.firstName, lastName: employee.lastName, street: employee.street, postcode: employee.postcode, city: employee.city, phone: employee.phone, skillSet: employee.skillSet?.map(skill => skill.id) || [], } } responseDtoToPutDto(employee: EmployeeResponseDTO): EmployeeRequestPutDTO { return { firstName: employee.firstName, lastName: employee.lastName, street: employee.street, postcode: employee.postcode, city: employee.city, phone: employee.phone, skillSet: employee.skillSet?.map(skill => skill.id) || [], } } createEmployee(employee: EmployeeResponseDTO) { this.http.post(`${SkillService.BASE_URL}/employees`, this.responseToRequestDto(employee)).subscribe(); } updateEmployee(employee: EmployeeResponseDTO) { this.http.put(`${SkillService.BASE_URL}/employees/${employee.id}`, this.responseDtoToPutDto(employee)).subscribe(); } getAllEmployees(): Observable> { return this.http.get>(`${SkillService.BASE_URL}/employees`); } deleteEmployee(id: number) { this.http.delete(`${SkillService.BASE_URL}/employees/${id}`).subscribe(); } getEmployeeById(id: number): Observable { return this.http.get(`${SkillService.BASE_URL}/employees/${id}`); } removeSkillFromEmployee(skillId: number, employeeId: number) { this.getEmployeeById(employeeId).subscribe(employee => { let employeePut = this.responseDtoToPutDto(employee); if (employeePut.skillSet.indexOf(skillId) != 1) { employeePut.skillSet = employeePut.skillSet.filter(skill => skill != skillId); } this.http.put(`${SkillService.BASE_URL}/employees/${employee.id}`, employeePut).subscribe(); }); } addSkillToEmployee(skillId: number, employee: EmployeeResponseDTO) { let employeePut = this.responseDtoToPutDto(employee); if (employeePut.skillSet.indexOf(skillId) == -1) { employeePut.skillSet.push(skillId); } this.http.put(`${SkillService.BASE_URL}/employees/${employee.id}`, employeePut).subscribe(); } }