41 lines
1008 B
TypeScript
41 lines
1008 B
TypeScript
type FetchOptions = {
|
|
method?: "GET" | "POST" | "PATCH" | "DELETE";
|
|
body?: unknown;
|
|
};
|
|
|
|
export function usePushApi() {
|
|
const config = useRuntimeConfig();
|
|
const token = useState<string>("push-admin-token", () => "");
|
|
|
|
const setToken = (nextToken: string) => {
|
|
token.value = nextToken.trim();
|
|
if (process.client) {
|
|
localStorage.setItem("fedeo-push-admin-token", token.value);
|
|
}
|
|
};
|
|
|
|
const hydrateToken = () => {
|
|
if (process.client && !token.value) {
|
|
token.value = localStorage.getItem("fedeo-push-admin-token") || "";
|
|
}
|
|
};
|
|
|
|
const request = async <T>(path: string, options: FetchOptions = {}) => {
|
|
hydrateToken();
|
|
return await $fetch<T>(`${config.public.apiBase}${path}`, {
|
|
method: options.method || "GET",
|
|
body: options.body as Record<string, any> | BodyInit | null | undefined,
|
|
headers: {
|
|
Authorization: `Bearer ${token.value}`,
|
|
},
|
|
});
|
|
};
|
|
|
|
return {
|
|
token,
|
|
setToken,
|
|
hydrateToken,
|
|
request,
|
|
};
|
|
}
|