auth.service.ts77 lines, 1.9 KB
| 1 | import { Injectable, HttpException } from '@nestjs/common'; |
| 2 | import { HttpService } from '@nestjs/axios'; |
| 3 | import { firstValueFrom } from 'rxjs'; |
| 4 | import { AuthResponse, SERVICES_PORTS, UserProfileResponse } from '@app/common'; |
| 5 | |
| 6 | @Injectable() |
| 7 | export class AuthService { |
| 8 | private readonly authServiceUrl = |
| 9 | process.env.AUTH_SERVICE_URL || |
| 10 | `http://localhost:${SERVICES_PORTS.AUTH_SERVICE}`; |
| 11 | |
| 12 | constructor(private readonly httpService: HttpService) {} |
| 13 | |
| 14 | async register(data: { |
| 15 | email: string; |
| 16 | password: string; |
| 17 | name: string; |
| 18 | }): Promise<UserProfileResponse> { |
| 19 | try { |
| 20 | const response = await firstValueFrom( |
| 21 | this.httpService.post<UserProfileResponse>( |
| 22 | `${this.authServiceUrl}/register`, |
| 23 | data, |
| 24 | ), |
| 25 | ); |
| 26 | |
| 27 | return response.data; |
| 28 | } catch (error) { |
| 29 | this.handleError(error); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | async login(data: { |
| 34 | email: string; |
| 35 | password: string; |
| 36 | }): Promise<AuthResponse> { |
| 37 | try { |
| 38 | const response = await firstValueFrom( |
| 39 | this.httpService.post<AuthResponse>( |
| 40 | `${this.authServiceUrl}/login`, |
| 41 | data, |
| 42 | ), |
| 43 | ); |
| 44 | |
| 45 | return response.data; |
| 46 | } catch (error) { |
| 47 | this.handleError(error); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | async getProfile(token: string): Promise<UserProfileResponse> { |
| 52 | try { |
| 53 | const response = await firstValueFrom( |
| 54 | this.httpService.get<UserProfileResponse>( |
| 55 | `${this.authServiceUrl}/profile`, |
| 56 | { |
| 57 | headers: { Authorization: token }, |
| 58 | }, |
| 59 | ), |
| 60 | ); |
| 61 | |
| 62 | return response.data; |
| 63 | } catch (error) { |
| 64 | this.handleError(error); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | private handleError(error: unknown): never { |
| 69 | const err = error as { |
| 70 | response?: { data: string | object; status: number }; |
| 71 | }; |
| 72 | if (err.response) { |
| 73 | throw new HttpException(err.response.data, err.response.status); |
| 74 | } |
| 75 | throw new HttpException('Something went wrong', 503); |
| 76 | } |
| 77 | } |