index.ts
28 lines
| 1 | import { AxiosResponse } from 'axios'; |
| 2 | |
| 3 | interface BaseApiResponse<T> { |
| 4 | success?: boolean; |
| 5 | data?: T; |
| 6 | error?: Error | string | null; |
| 7 | } |
| 8 | |
| 9 | export const generateCorrelationId = (): string => `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; |
| 10 | |
| 11 | export const asyncCall = async <T>( |
| 12 | promise: Promise<AxiosResponse<BaseApiResponse<T>>> |
| 13 | ): Promise<[T | null, Error | null]> => { |
| 14 | try { |
| 15 | const response = await promise; |
| 16 | |
| 17 | if (!response.data.error || (Array.isArray(response.data.error) && !response.data.error.length)) { |
| 18 | const responseData = response.data.data || response.data; |
| 19 | |
| 20 | return [responseData as T, null]; |
| 21 | } |
| 22 | |
| 23 | return [null, response.data.error as Error]; |
| 24 | } catch (error) { |
| 25 | return [null, error as Error]; |
| 26 | } |
| 27 | }; |
| 28 |