tagsServiceClient.ts83 lines, 2.0 KB
| 1 | import { createServiceError } from "../../../shared/utils"; |
| 2 | import axios from "axios"; |
| 3 | import { valid } from "joi"; |
| 4 | |
| 5 | export interface TagValidationResponse { |
| 6 | validTags: Array<{ |
| 7 | id: string; |
| 8 | name: string; |
| 9 | color?: string; |
| 10 | userId: string; |
| 11 | createdAt: Date; |
| 12 | }>; |
| 13 | invalidTagIds: string[]; |
| 14 | } |
| 15 | |
| 16 | export class TagsServiceClient { |
| 17 | private baseUrl: string; |
| 18 | |
| 19 | constructor() { |
| 20 | this.baseUrl = process.env.TAGS_SERVICE_URL || "http://localhost:3004"; |
| 21 | } |
| 22 | |
| 23 | async validateTags( |
| 24 | tagsIds: string[], |
| 25 | authToken: string |
| 26 | ): Promise<TagValidationResponse> { |
| 27 | try { |
| 28 | const response = await axios.post( |
| 29 | `${this.baseUrl}/tags/validate`, |
| 30 | { |
| 31 | tagsIds, |
| 32 | }, |
| 33 | { |
| 34 | headers: { |
| 35 | "Content-Type": "application/json", |
| 36 | Authorization: `Bearer ${authToken}`, |
| 37 | }, |
| 38 | timeout: 5000, |
| 39 | } |
| 40 | ); |
| 41 | |
| 42 | if (!response.data.success) { |
| 43 | throw createServiceError("Tag validation failed", 400); |
| 44 | } |
| 45 | |
| 46 | return response.data.data; |
| 47 | } catch (error) { |
| 48 | if (error.response) { |
| 49 | // tags service retruned an eror |
| 50 | const statusCode = error.response?.status || 500; |
| 51 | const message = error.response?.data?.error || "Tag validation failed"; |
| 52 | throw createServiceError(message, statusCode); |
| 53 | } else if (error.request) { |
| 54 | // Tags service did not respond |
| 55 | throw createServiceError("Tags service is unavailable", 503); |
| 56 | } else { |
| 57 | // Something else happened |
| 58 | throw createServiceError("An unexpected error occurred", 500); |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | async getTagsByIds( |
| 64 | tags: string[], |
| 65 | authToken: string |
| 66 | ): Promise< |
| 67 | Array<{ |
| 68 | id: string; |
| 69 | name: string; |
| 70 | color?: string; |
| 71 | userId: string; |
| 72 | createdAt: Date; |
| 73 | }> |
| 74 | > { |
| 75 | const validation = await this.validateTags(tags, authToken); |
| 76 | |
| 77 | if (validation.invalidTagIds.length > 0) { |
| 78 | throw createServiceError("Invalid tag ids", 400); |
| 79 | } |
| 80 | |
| 81 | return validation.validTags; |
| 82 | } |
| 83 | } |