|
| 1 | +import { ref, onMounted, watch } from 'vue'; |
| 2 | +import { useKeycloak } from '@dsb-norge/vue-keycloak-js'; |
| 3 | +import type { BaseField } from '@pdc/sdk'; |
| 4 | +import { getLogger } from '@/logger'; |
| 5 | + |
| 6 | +const logger = getLogger('pdc-api'); |
| 7 | +const API_URL = import.meta.env.VITE_API_URL; |
| 8 | + |
| 9 | +const { token } = useKeycloak(); |
| 10 | + |
| 11 | +function throwIfNotOk(res: Response) { |
| 12 | + if (!res.ok) { |
| 13 | + throw new Error(`Response status: ${res.status} ${res.statusText}`); |
| 14 | + } |
| 15 | + return res; |
| 16 | +} |
| 17 | + |
| 18 | +export function usePdcApi<T>(path: string, params = new URLSearchParams()) { |
| 19 | + const data = ref<T | null>(null); |
| 20 | + |
| 21 | + const fetchData = async () => { |
| 22 | + data.value = null; |
| 23 | + try { |
| 24 | + const url = new URL(path, API_URL); |
| 25 | + url.search = params.toString(); |
| 26 | + |
| 27 | + const res = await fetch(url.toString(), { |
| 28 | + headers: { Authorization: `Bearer ${token}` }, |
| 29 | + }).then(throwIfNotOk); |
| 30 | + |
| 31 | + data.value = (await res.json()) as T; |
| 32 | + } catch (err) { |
| 33 | + logger.error( |
| 34 | + { error: err, params: params.toString() }, |
| 35 | + `Error fetching ${path}`, |
| 36 | + ); |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + onMounted(fetchData); |
| 41 | + |
| 42 | + watch(() => params.toString(), fetchData); |
| 43 | + |
| 44 | + return { data, fetchData }; |
| 45 | +} |
| 46 | + |
| 47 | +export function useBaseFields() { |
| 48 | + return usePdcApi<BaseField[]>('/baseFields'); |
| 49 | +} |
0 commit comments