authClient.ts44 lines, 1.2 KB
| 1 | import { JWTPayload, ServiceResponse } from "../../../shared/types"; |
| 2 | import { createServiceError } from "../../../shared/utils"; |
| 3 | import axios from "axios"; |
| 4 | |
| 5 | export class AuthClient { |
| 6 | private readonly authServiceUrl: string; |
| 7 | |
| 8 | constructor() { |
| 9 | this.authServiceUrl = |
| 10 | process.env.AUTH_SERVICE_URL || "http://localhost:3001"; |
| 11 | } |
| 12 | |
| 13 | async validateToken(token: string): Promise<JWTPayload> { |
| 14 | try { |
| 15 | const response = await axios.post<ServiceResponse<JWTPayload>>( |
| 16 | `${this.authServiceUrl}/auth/validate`, |
| 17 | {}, |
| 18 | { |
| 19 | headers: { |
| 20 | Authorization: `Bearer ${token}`, |
| 21 | }, |
| 22 | timeout: 5000, |
| 23 | } |
| 24 | ); |
| 25 | |
| 26 | if (!response.data.success || !response.data.data) { |
| 27 | throw createServiceError( |
| 28 | "Invalid token response from auth service", |
| 29 | 401 |
| 30 | ); |
| 31 | } |
| 32 | |
| 33 | return response.data.data; |
| 34 | } catch (error) { |
| 35 | if (axios.isAxiosError(error)) { |
| 36 | throw createServiceError("Invalid or expired token", 401); |
| 37 | } |
| 38 | if (error.code === "ECONNRREFUSED") { |
| 39 | throw createServiceError("Auth service is unavailable", 503); |
| 40 | } |
| 41 | throw createServiceError("An unexpected error occurred", 500); |
| 42 | } |
| 43 | } |
| 44 | } |