next/lib/client/middleware.ts

49 lines
1.9 KiB
TypeScript
Raw Normal View History

import { SingleChapterResult } from "./types/slightlyDifferentStory";
import { IChapter } from "@models/stories/chapter";
import { IStory } from "@models/stories";
import { messages } from "@server/constants";
import { IUser } from "@models/user";
2023-12-29 20:53:29 -05:00
import { IDraft } from "@models/stories/draft";
const show404 = () => showError({ statusCode: 404, message: messages[404] });
export const storyMiddleware = defineNuxtRouteMiddleware(async (to, from) => {
const { getSession } = useAuth();
await getSession({ force: true });
const { data } = useAuth();
console.log("to n from", to, from, data);
2023-12-29 20:53:29 -05:00
const { data: story, error } = await useApiFetch<SingleChapterResult>(to.path);
if (error.value) {
return showError(error.value);
} else if (!story.value) {
return showError({ statusCode: 404, message: messages[404] });
}
console.log("fns", story, error);
if (!data?.value?.user && story.value?.currentChapter.loggedInOnly) {
return navigateTo("/login");
}
});
2023-12-29 20:53:29 -05:00
export const storyEditMiddleware = defineNuxtRouteMiddleware(async (to, from) => {
const { data: curU } = useAuth();
const { data: storyInfo } = await useApiFetch<({ chapters: (IChapter & { text: string })[] } & IStory) | null>(`/story/${to.params.id}/full`);
2023-12-29 20:53:29 -05:00
if (!storyInfo.value) show404();
if (curU.value?.user?._id !== (storyInfo.value?.author as IUser)._id && curU.value?.user?._id !== (storyInfo.value?.coAuthor as IUser)?._id) {
return showError({
statusCode: 403,
message: messages[403],
});
}
});
export const draftEditMiddleware = defineNuxtRouteMiddleware(async (to, from) => {
const { data: curU } = useAuth();
const { data: storyInfo } = await useApiFetch<IDraft | null>(`/draft/${to.params.id}`);
2023-12-29 20:53:29 -05:00
if (!storyInfo.value) show404();
if (curU.value?.user?._id !== (storyInfo.value?.author as IUser)._id && curU.value?.user?._id !== (storyInfo.value?.coAuthor as IUser)?._id) {
return showError({
statusCode: 403,
message: messages[403],
});
}
});