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