Skip to content

Commit 6425e4d

Browse files
committed
Add custom pdc-api hook
This commit 'migrates' our generic api hook for fetching resources from the pdc-api, replacing react's reactivity and state-based functions with those from vue. Also, our new auth package sadly does not provide an authorized fetch function, so we are instead using it's getToken hook and adding that to our fetch header. In trying to recreate the exisiting react function as closely as possible, there is likely room here for making things more vue-y in the future. But having tested locally it seems to function as expected. Similar to react's useEffect, we would want to call the fetchData function as the callback to vue's onMounted lifecylce hook. Issue #1009 Rebuild frontend in Vue
1 parent 4b1393c commit 6425e4d

File tree

2 files changed

+49
-60
lines changed

2 files changed

+49
-60
lines changed

oldSrc/pdc-api.ts

Lines changed: 0 additions & 60 deletions
This file was deleted.

src/pdc-api.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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

Comments
 (0)