ln/app/client/pages/work/book/$bookId/chapter/new.tsx
2025-06-01 17:54:57 +03:00

88 lines
2.1 KiB
TypeScript

import { gql, useQuery } from '@apollo/client';
import { BookChapterForm } from '@app/client/components/BookChapterForm';
import { useIdentity } from '@app/client/hooks/identity';
import { useToastMutation } from '@app/client/hooks/useToastMutation';
import { Skeleton } from '@chakra-ui/react';
import { BookChapterNewCreateMutation, BookChapterNewQuery } from '@generated/types';
import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router';
import { bookChapterListQuery } from '../overview/contents';
export const Route = createFileRoute('/work/book/$bookId/chapter/new')({
component: RouteComponent,
beforeLoad: ({ context }) => {
if (!context.isAuthenticated) throw redirect({ to: '/' });
}
});
function RouteComponent() {
const { bookId: id } = Route.useParams();
const identity = useIdentity();
const navigate = useNavigate();
const { data } = useQuery<BookChapterNewQuery>(query, {
variables: { id }
});
const { update: chapterCreate } = useToastMutation<BookChapterNewCreateMutation>({
mutation,
successMsg: 'Chapter created successfully',
refetchQueries: [bookChapterListQuery]
});
if (data == null) return <Skeleton />;
if (identity?.data.user.id !== data.bookOne.author.id)
throw redirect({ to: `/work/book/${id}/overview/contents` });
return (
<BookChapterForm
bookId={id}
onChapterSubmit={async chapter => {
await chapterCreate({
variables: {
input: {
bookId: id,
...chapter
}
}
});
navigate({ to: `/work/book/${id}/overview/contents` });
}}
/>
);
}
const query = gql`
query BookChapterNew($id: ID!) {
bookOne(id: $id) {
id
author {
id
}
}
}
`;
const mutation = gql`
mutation BookChapterNewCreate($input: BookChapterCreateInput!) {
bookChapterCreate(input: $input) {
id
title
foreword
footnote
content
previousChapterId
nextChapterId
book {
id
updatedAt
wordsTotal
chaptersTotal
author {
id
}
}
}
}
`;