-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathappFetch.ts
98 lines (91 loc) · 2.51 KB
/
appFetch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// TODO : remove that
import { NitroFetchOptions, NitroFetchRequest } from "nitropack";
import { useAuthUser } from "~/store/auth";
import { API_URL } from "~/constants/http";
export default defineNuxtPlugin(() => {
const store = useAuthUser();
const event = useRequestEvent();
const headers: {
[key: string]: string;
} = {
...(useRequestHeaders(["cookie"]) as {
[key: string]: string;
}),
...{
accept: "application/json",
},
};
const handleException = (e: any) => {
logger.error("An error hapenned during an API call");
logger.error(e);
// Check if 401 so remove auth info
if (e && e.response && e.response.status === 401 && store.isAuthenticated) {
logger.error("401 error, removing authentication informations");
store.resetAuth();
}
const cookies = e.response.headers.get("set-cookie") || "";
if (process.server && cookies) {
event.node.res.setHeader("set-cookie", cookies);
}
throw e;
};
const fetchRaw = async <T>(
request: NitroFetchRequest,
opts?: NitroFetchOptions<"json">
) => {
const res = await $fetch.raw<T>(request, {
headers,
baseURL: API_URL,
...opts,
});
const cookies = res.headers.get("set-cookie") || "";
if (process.server && cookies) {
event.node.res.setHeader("set-cookie", cookies);
}
return res;
};
const fetchNative = async <T>(
request: NitroFetchRequest,
opts?: NitroFetchOptions<"json">
) => {
const res = await $fetch.raw<T>(request, {
headers,
baseURL: API_URL,
...opts,
});
const cookies = res.headers.get("set-cookie") || "";
if (process.server && cookies) {
event.node.res.setHeader("set-cookie", cookies);
}
return res._data;
};
const _appFetchRaw = async <T>(
request: NitroFetchRequest,
opts?: NitroFetchOptions<"json">
) => {
try {
return await fetchRaw<T>(request, opts);
} catch (e: any) {
handleException(e);
}
};
const appFetch = async <T>(
request: NitroFetchRequest,
opts?: NitroFetchOptions<"json">
) => {
try {
return await fetchNative<T>(request, opts);
} catch (e: any) {
handleException(e);
}
};
appFetch.raw = _appFetchRaw;
// When you use appFetch.create, you should ensure that you dont need to bridge cookies
appFetch.create = $fetch.create;
return {
provide: {
// // https://nuxt.com/docs/getting-started/data-fetching#example-pass-client-headers-to-the-api
appFetch,
},
};
});