profileShare

rasmusjy / splitapp-frontend-vue

Read-only snapshot

No repository description.

main default branch 96 files Expires Sep 13, 2026, 9:06 AM
PollService.ts 2,358 bytes
1 import httpClient from '@/services/httpClient'
2 import type { IResultObject } from '@/types/IResultObject'
3 import type { IPoll, IPollCreate } from '@/types/IPoll'
4 import axios from 'axios'
5
6 export default class PollService {
7 static async getByTrip(tripId: string): Promise<IResultObject<IPoll[]>> {
8 try {
9 const response = await httpClient.get<IPoll[]>(`Polls/trip/${tripId}`)
10 return { data: response.data }
11 } catch (e) {
12 return { errors: PollService.handleError(e) }
13 }
14 }
15
16 static async getById(id: string): Promise<IResultObject<IPoll>> {
17 try {
18 const response = await httpClient.get<IPoll>(`Polls/${id}`)
19 return { data: response.data }
20 } catch (e) {
21 return { errors: PollService.handleError(e) }
22 }
23 }
24
25 static async create(entity: IPollCreate): Promise<IResultObject<IPoll>> {
26 try {
27 const response = await httpClient.post<IPoll>('Polls', entity)
28 return { data: response.data }
29 } catch (e) {
30 return { errors: PollService.handleError(e) }
31 }
32 }
33
34 static async vote(pollId: string, optionId: string): Promise<IResultObject<void>> {
35 try {
36 await httpClient.post(`Polls/${pollId}/vote`, { optionId })
37 return { data: undefined }
38 } catch (e) {
39 return { errors: PollService.handleError(e) }
40 }
41 }
42
43 static async close(id: string): Promise<IResultObject<void>> {
44 try {
45 await httpClient.post(`Polls/${id}/close`)
46 return { data: undefined }
47 } catch (e) {
48 return { errors: PollService.handleError(e) }
49 }
50 }
51
52 static async delete(id: string): Promise<IResultObject<void>> {
53 try {
54 await httpClient.delete(`Polls/${id}`)
55 return { data: undefined }
56 } catch (e) {
57 return { errors: PollService.handleError(e) }
58 }
59 }
60
61 private static handleError(e: unknown): string[] {
62 if (axios.isAxiosError(e)) {
63 const data = e.response?.data
64 if (data?.errors && typeof data.errors === 'object') {
65 const messages: string[] = []
66 for (const field of Object.values(data.errors)) {
67 if (Array.isArray(field)) messages.push(...field)
68 }
69 if (messages.length > 0) return messages
70 }
71 if (data?.title) return [data.title]
72 return [e.response?.statusText ?? 'Unknown error']
73 }
74 return ['Network error or server unavailable']
75 }
76 }
77