CurrencyService.ts
1,058 bytes
| 1 | import httpClient from '@/services/httpClient' |
|---|---|
| 2 | import type { IResultObject } from '@/types/IResultObject' |
| 3 | import type { ICurrency } from '@/types/ICurrency' |
| 4 | import axios from 'axios' |
| 5 | |
| 6 | export default class CurrencyService { |
| 7 | static async getAll(): Promise<IResultObject<ICurrency[]>> { |
| 8 | try { |
| 9 | const response = await httpClient.get<ICurrency[]>('Currencies') |
| 10 | return { data: response.data } |
| 11 | } catch (e) { |
| 12 | return { errors: CurrencyService.handleError(e) } |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | private static handleError(e: unknown): string[] { |
| 17 | if (axios.isAxiosError(e)) { |
| 18 | const data = e.response?.data |
| 19 | if (data?.errors && typeof data.errors === 'object') { |
| 20 | const messages: string[] = [] |
| 21 | for (const field of Object.values(data.errors)) { |
| 22 | if (Array.isArray(field)) messages.push(...field) |
| 23 | } |
| 24 | if (messages.length > 0) return messages |
| 25 | } |
| 26 | if (data?.title) return [data.title] |
| 27 | return [e.response?.statusText ?? 'Unknown error'] |
| 28 | } |
| 29 | return ['Network error or server unavailable'] |
| 30 | } |
| 31 | } |
| 32 | |