BudgetCategoryService.ts
2,027 bytes
| 1 | import httpClient from '@/services/httpClient' |
|---|---|
| 2 | import type { IResultObject } from '@/types/IResultObject' |
| 3 | import type { IBudgetCategory, IBudgetCategoryCreate } from '@/types/IBudgetCategory' |
| 4 | import axios from 'axios' |
| 5 | |
| 6 | export default class BudgetCategoryService { |
| 7 | static async getByTrip(tripId: string): Promise<IResultObject<IBudgetCategory[]>> { |
| 8 | try { |
| 9 | const response = await httpClient.get<IBudgetCategory[]>(`BudgetCategories/trip/${tripId}`) |
| 10 | return { data: response.data } |
| 11 | } catch (e) { |
| 12 | return { errors: BudgetCategoryService.handleError(e) } |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | static async create(entity: IBudgetCategoryCreate): Promise<IResultObject<IBudgetCategory>> { |
| 17 | try { |
| 18 | const response = await httpClient.post<IBudgetCategory>('BudgetCategories', entity) |
| 19 | return { data: response.data } |
| 20 | } catch (e) { |
| 21 | return { errors: BudgetCategoryService.handleError(e) } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | static async update(id: string, entity: IBudgetCategoryCreate): Promise<IResultObject<void>> { |
| 26 | try { |
| 27 | await httpClient.put(`BudgetCategories/${id}`, entity) |
| 28 | return { data: undefined } |
| 29 | } catch (e) { |
| 30 | return { errors: BudgetCategoryService.handleError(e) } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | static async delete(id: string): Promise<IResultObject<void>> { |
| 35 | try { |
| 36 | await httpClient.delete(`BudgetCategories/${id}`) |
| 37 | return { data: undefined } |
| 38 | } catch (e) { |
| 39 | return { errors: BudgetCategoryService.handleError(e) } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | private static handleError(e: unknown): string[] { |
| 44 | if (axios.isAxiosError(e)) { |
| 45 | const data = e.response?.data |
| 46 | if (data?.errors && typeof data.errors === 'object') { |
| 47 | const messages: string[] = [] |
| 48 | for (const field of Object.values(data.errors)) { |
| 49 | if (Array.isArray(field)) messages.push(...field) |
| 50 | } |
| 51 | if (messages.length > 0) return messages |
| 52 | } |
| 53 | if (data?.title) return [data.title] |
| 54 | return [e.response?.statusText ?? 'Unknown error'] |
| 55 | } |
| 56 | return ['Network error or server unavailable'] |
| 57 | } |
| 58 | } |
| 59 | |