owltide/composables/session.ts

35 lines
882 B
TypeScript
Raw Normal View History

import { appendResponseHeader } from "h3";
import type { H3Event } from "h3";
const fetchWithCookie = async (url: string, event?: H3Event) => {
if (!event) {
return $fetch(url);
}
const cookie = useRequestHeader("cookie");
const res = await $fetch.raw(url, {
headers: cookie ? { cookie } : undefined
});
for (const cookie of res.headers.getSetCookie()) {
appendResponseHeader(event, "set-cookie", cookie);
}
return res._data;
}
export const useAccountSession = () => {
const event = useRequestEvent();
return useAsyncData(
"session",
async () => await fetchWithCookie("/api/auth/session", event),
{
transform: (input) => input === undefined ? false as any as null: input,
getCachedData(key, nuxtApp, context) {
if (context.cause === "refresh:manual")
return undefined
return nuxtApp.payload.data[key];
},
dedupe: "defer",
}
);
}