Refactor API integration and data fetching for genre, novel, and chapter pages

- Replace Prisma database calls with API fetches from the reader API in GenreDetailPage, GenresPage, SearchPage, ChapterReaderPage, and NovelDetailPage.
- Introduce new utility functions for API requests in server-api.ts, including error handling.
- Update authentication flow in auth.ts to sync Google login with the reader API.
- Modify NextAuth session and JWT types to include additional user information.
- Clean up unused imports and code related to Prisma and MongoDB connections.
- Adjust the configuration in next.config.mjs to remove unnecessary API routes.
This commit is contained in:
2026-03-30 13:54:51 +07:00
parent f9bb247ff1
commit 41aca718c9
12 changed files with 515 additions and 749 deletions
+58 -51
View File
@@ -5,12 +5,41 @@ import { Button } from "@/components/ui/button"
import { CommentSection } from "@/components/comment-section"
import { ReaderFAB } from "@/components/reader-fab"
import { ChapterReaderProgress } from "./chapter-reader-progress"
import { prisma } from "@/lib/prisma"
import connectToMongoDB from "@/lib/mongoose"
import { Chapter as ChapterModel } from "@/lib/models/chapter"
import { readerApiFetch, readerApiFetchNullable } from "@/lib/server-api"
export const dynamic = "force-dynamic"
type NovelDetail = {
id: string
title: string
slug: string
}
type ChapterDetail = {
id: string
novelId: string
number: number
title: string
content: string
volumeNumber?: number | null
volumeTitle?: string | null
volumeChapterNumber?: number | null
prevChapterNumber?: number | null
nextChapterNumber?: number | null
maxChapter: number
}
type CommentsResponse = {
comments: Array<{
id: string
userId: string
username: string
content: string
chapterId?: string | null
createdAt: string | null
}>
}
export default async function ChapterReaderPage({ params }: { params: Promise<{ slug: string; chapterId: string }> }) {
const { slug, chapterId } = await params
const chapterNumber = parseInt(chapterId, 10)
@@ -19,57 +48,41 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
notFound()
}
const novel = await prisma.novel.findUnique({
where: { slug }
})
const novel = await readerApiFetchNullable<NovelDetail>(`/api/novels/${encodeURIComponent(slug)}`)
if (!novel) {
notFound()
}
await connectToMongoDB()
const chapter = await ChapterModel.findOne({ novelId: novel.id, number: chapterNumber }).lean()
const chapter = await readerApiFetchNullable<ChapterDetail>(`/api/truyen/${encodeURIComponent(novel.id)}/chapters/by-number/${chapterNumber}`)
if (!chapter) {
notFound()
}
const maxChapter = await ChapterModel.countDocuments({ novelId: novel.id })
const commentsData = await readerApiFetch<CommentsResponse>(
`/api/truyen/${encodeURIComponent(novel.id)}/comments?chapterId=${encodeURIComponent(chapter.id)}&page=1&limit=50`
)
const commentsData = await prisma.comment.findMany({
where: { novelId: novel.id, chapterId: chapter._id.toString() },
include: { user: true },
orderBy: { createdAt: "desc" }
})
const comments = commentsData.map(c => ({
id: c.id,
userId: c.user.id,
username: c.user.name || "User",
avatarColor: c.user.image || "bg-primary",
novelId: c.novelId,
chapterId: c.chapterId || undefined,
content: c.content,
createdAt: c.createdAt.toISOString().split("T")[0]
const comments = commentsData.comments.map((comment) => ({
id: comment.id,
userId: comment.userId,
username: comment.username || "User",
avatarColor: "bg-primary",
novelId: novel.id,
chapterId: comment.chapterId || undefined,
content: comment.content,
createdAt: comment.createdAt ? comment.createdAt.split("T")[0] : "",
}))
// Increment chapter views quietly (fire and forget to not block render)
ChapterModel.updateOne({ _id: chapter._id }, { $inc: { views: 1 } })
.catch(e => console.error("Error updating chapter views:", e))
const hasPrev = chapterNumber > 1
const hasNext = chapterNumber < maxChapter
// Extract paragraphs for TTS
const hasPrev = Boolean(chapter.prevChapterNumber)
const hasNext = Boolean(chapter.nextChapterNumber)
const paragraphs = chapter.content.split("\n").map((p: string) => p.trim()).filter(Boolean)
const chapterLabel = (chapter as any).volumeChapterNumber ? `Chương ${(chapter as any).volumeChapterNumber}` : `Chương ${chapter.number}`
const volumeLabel = (chapter as any).volumeTitle || ((chapter as any).volumeNumber ? `Quyển ${(chapter as any).volumeNumber}` : null)
const chapterLabel = chapter.volumeChapterNumber ? `Chương ${chapter.volumeChapterNumber}` : `Chương ${chapter.number}`
const volumeLabel = chapter.volumeTitle || (chapter.volumeNumber ? `Quyển ${chapter.volumeNumber}` : null)
return (
<div className="mx-auto max-w-4xl px-3 py-4 md:px-8 md:py-6 lg:max-w-screen-lg">
{/* Top navigation */}
<div className="mb-6 flex flex-col gap-3">
<Link href={`/truyen/${slug}`} className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors">
<Link href={`/truyen/${slug}`} className="inline-flex items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-foreground">
<ChevronLeft className="h-4 w-4" /> {novel.title}
</Link>
@@ -80,11 +93,10 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
</div>
</div>
{/* Chapter navigation top */}
<div className="mb-6 flex items-center justify-between gap-2">
<Button variant="outline" size="sm" disabled={!hasPrev} asChild={hasPrev}>
{hasPrev ? (
<Link href={`/truyen/${slug}/${chapterNumber - 1}`}>
<Link href={`/truyen/${slug}/${chapter.prevChapterNumber}`}>
<ChevronLeft className="mr-1 h-4 w-4" />
<span className="hidden sm:inline">Ch. trước</span>
<span className="sm:hidden">Trước</span>
@@ -104,7 +116,7 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
</Button>
<Button variant="outline" size="sm" disabled={!hasNext} asChild={hasNext}>
{hasNext ? (
<Link href={`/truyen/${slug}/${chapterNumber + 1}`}>
<Link href={`/truyen/${slug}/${chapter.nextChapterNumber}`}>
<span className="hidden sm:inline">Ch. sau</span>
<span className="sm:hidden">Sau</span>
<ChevronRight className="ml-1 h-4 w-4" />
@@ -119,7 +131,6 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
</Button>
</div>
{/* Chapter content */}
<article className="chapter-content mb-8 rounded-lg border border-border bg-card p-4 font-serif text-foreground/90 text-justify md:p-8 lg:p-12">
{paragraphs.map((text: string, idx: number) => (
<p key={idx} data-p-index={idx} className="mb-4 last:mb-0">
@@ -128,11 +139,10 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
))}
</article>
{/* Chapter navigation bottom */}
<div className="mb-8 flex items-center justify-between gap-2">
<Button variant="outline" size="sm" disabled={!hasPrev} asChild={hasPrev}>
{hasPrev ? (
<Link href={`/truyen/${slug}/${chapterNumber - 1}`}>
<Link href={`/truyen/${slug}/${chapter.prevChapterNumber}`}>
<ChevronLeft className="mr-1 h-4 w-4" />
<span className="hidden sm:inline">Chương trước</span>
<span className="sm:hidden">Trước</span>
@@ -147,7 +157,7 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
</Button>
<Button variant="outline" size="sm" disabled={!hasNext} asChild={hasNext}>
{hasNext ? (
<Link href={`/truyen/${slug}/${chapterNumber + 1}`}>
<Link href={`/truyen/${slug}/${chapter.nextChapterNumber}`}>
<span className="hidden sm:inline">Chương sau</span>
<span className="sm:hidden">Sau</span>
<ChevronRight className="ml-1 h-4 w-4" />
@@ -162,21 +172,18 @@ export default async function ChapterReaderPage({ params }: { params: Promise<{
</Button>
</div>
{/* Save reading progress */}
<ChapterReaderProgress novelId={novel.id} chapterId={chapter._id.toString()} chapterNumber={chapter.number} />
<ChapterReaderProgress novelId={novel.id} chapterId={chapter.id} chapterNumber={chapter.number} />
{/* Comments */}
<section className="border-t border-border pt-8">
<CommentSection comments={comments} novelId={novel.id} chapterId={chapter._id.toString()} />
<CommentSection comments={comments} novelId={novel.id} chapterId={chapter.id} />
</section>
{/* Floating Reader Actions & TTS Player */}
<ReaderFAB
novelId={novel.id}
novelSlug={slug}
paragraphs={paragraphs}
currentChapter={chapterNumber}
maxChapter={maxChapter}
maxChapter={chapter.maxChapter}
chapterTitle={`${volumeLabel ? `${volumeLabel} - ` : ""}${chapterLabel}: ${chapter.title}`}
/>
</div>
+110 -93
View File
@@ -7,13 +7,76 @@ import { StarRating } from "@/components/star-rating"
import { ChapterList } from "@/components/chapter-list"
import { CommentSection } from "@/components/comment-section"
import { NovelDetailActions } from "./novel-detail-actions"
import { prisma } from "@/lib/prisma"
import connectToMongoDB from "@/lib/mongoose"
import { Chapter } from "@/lib/models/chapter"
import { getNovelStatusBadgeClass } from "@/lib/novel-status"
import { readerApiFetch, readerApiFetchNullable } from "@/lib/server-api"
export const dynamic = "force-dynamic"
type NovelGenre = {
id: string
name: string
slug: string
}
type SeriesNovel = {
id: string
slug: string
title: string
status: string
totalChapters: number
coverUrl: string | null
}
type NovelDetail = {
id: string
title: string
slug: string
originalTitle: string | null
authorName: string
originalAuthorName: string | null
description: string | null
coverUrl: string | null
status: string
totalChapters: number
views: number
ratingCount: number
bookmarkCount: number
seriesId: string | null
genres: NovelGenre[]
series: {
id: string
name: string
slug: string
novels: SeriesNovel[]
} | null
}
type ChaptersResponse = {
chapters: Array<{
id: string
number: number
title: string
views: number
createdAt: string | null
volumeNumber?: number | null
volumeTitle?: string | null
volumeChapterNumber?: number | null
}>
totalChapters: number
totalPages: number
}
type CommentsResponse = {
comments: Array<{
id: string
userId: string
username: string
content: string
chapterId?: string | null
createdAt: string | null
}>
}
export default async function NovelDetailPage({
params,
searchParams
@@ -24,17 +87,10 @@ export default async function NovelDetailPage({
const { slug } = await params
const { page } = await searchParams
const currentPage = parseInt(page || "1")
const currentPage = Math.max(1, parseInt(page || "1", 10) || 1)
const limit = 20
const novel = await prisma.novel.findUnique({
where: { slug },
include: {
genres: {
include: { genre: true }
}
}
})
const novel = await readerApiFetchNullable<NovelDetail>(`/api/novels/${encodeURIComponent(slug)}`)
if (!novel) {
notFound()
@@ -51,97 +107,58 @@ export default async function NovelDetailPage({
status: string
totalChapters: number
coverUrl: string | null
updatedAt: Date
}> = []
const [firstChapterData, commentsData, chapterCommentsData, chaptersData] = await Promise.all([
readerApiFetch<ChaptersResponse>(`/api/truyen/${encodeURIComponent(novel.id)}/chapters?page=1&limit=1`),
readerApiFetch<CommentsResponse>(`/api/truyen/${encodeURIComponent(novel.id)}/comments?page=1&limit=50`),
readerApiFetch<CommentsResponse>(`/api/truyen/${encodeURIComponent(novel.id)}/comments?scope=chapter&page=1&limit=50`),
novel.seriesId
? Promise.resolve(null)
: readerApiFetch<ChaptersResponse>(`/api/truyen/${encodeURIComponent(novel.id)}/chapters?page=${currentPage}&limit=${limit}`),
])
await connectToMongoDB()
firstChapterNumber = firstChapterData.chapters[0]?.number
if (novel.seriesId) {
const [firstChapter, volumes] = await Promise.all([
Chapter.findOne({ novelId: novel.id }).sort({ number: 1 }).select("number").lean(),
prisma.novel.findMany({
where: { seriesId: novel.seriesId },
select: {
id: true,
slug: true,
title: true,
status: true,
totalChapters: true,
coverUrl: true,
updatedAt: true,
},
orderBy: { createdAt: "asc" },
}),
])
firstChapterNumber = (firstChapter as any)?.number
seriesVolumes = volumes
} else {
const skip = (currentPage - 1) * limit
const [chapters, chaptersCount, firstChapter] = await Promise.all([
Chapter.find({ novelId: novel.id })
.sort({ number: 1 })
.skip(skip)
.limit(limit)
.select("id novelId number title createdAt views volumeNumber volumeTitle volumeChapterNumber")
.lean(),
Chapter.countDocuments({ novelId: novel.id }),
Chapter.findOne({ novelId: novel.id }).sort({ number: 1 }).select("number").lean(),
])
totalChapters = chaptersCount
totalPages = Math.ceil(totalChapters / limit)
firstChapterNumber = (firstChapter as any)?.number
formattedChapters = chapters.map(c => ({
id: c._id.toString(),
novelId: c.novelId,
number: c.number,
volumeNumber: (c as any).volumeNumber ?? null,
volumeTitle: (c as any).volumeTitle ?? null,
volumeChapterNumber: (c as any).volumeChapterNumber ?? null,
title: c.title,
createdAt: c.createdAt ? (c.createdAt as Date).toISOString() : new Date().toISOString(),
views: c.views || 0,
content: ""
seriesVolumes = novel.series?.novels || []
} else if (chaptersData) {
totalChapters = chaptersData.totalChapters
totalPages = Math.max(1, chaptersData.totalPages || 1)
formattedChapters = chaptersData.chapters.map((chapter) => ({
id: chapter.id,
novelId: novel.id,
number: chapter.number,
volumeNumber: chapter.volumeNumber ?? null,
volumeTitle: chapter.volumeTitle ?? null,
volumeChapterNumber: chapter.volumeChapterNumber ?? null,
title: chapter.title,
createdAt: chapter.createdAt ? chapter.createdAt.split("T")[0] : "",
views: chapter.views || 0,
content: "",
}))
}
const commentsData = await prisma.comment.findMany({
where: { novelId: novel.id, chapterId: null },
include: { user: true },
orderBy: { createdAt: "desc" }
})
// Format explicitly as the CommentProp type
const comments = commentsData.map(c => ({
id: c.id,
userId: c.user.id,
username: c.user.name || "User",
avatarColor: c.user.image || "bg-primary",
novelId: c.novelId,
content: c.content,
createdAt: c.createdAt.toISOString().split("T")[0]
const comments = commentsData.comments.map((comment) => ({
id: comment.id,
userId: comment.userId,
username: comment.username || "User",
avatarColor: "bg-primary",
novelId: novel.id,
content: comment.content,
createdAt: comment.createdAt ? comment.createdAt.split("T")[0] : "",
}))
const chapterCommentsData = await prisma.comment.findMany({
where: { novelId: novel.id, chapterId: { not: null } },
include: { user: true },
orderBy: { createdAt: "desc" }
})
// Format explicitly as the CommentProp type
const chapterComments = chapterCommentsData.map(c => ({
id: c.id,
userId: c.user.id,
username: c.user.name || "User",
avatarColor: c.user.image || "bg-primary",
novelId: c.novelId,
content: c.content,
createdAt: c.createdAt.toISOString().split("T")[0]
const chapterComments = chapterCommentsData.comments.map((comment) => ({
id: comment.id,
userId: comment.userId,
username: comment.username || "User",
avatarColor: "bg-primary",
novelId: novel.id,
content: comment.content,
createdAt: comment.createdAt ? comment.createdAt.split("T")[0] : "",
}))
const novelGenres = novel.genres.map(ng => ng.genre) || []
const novelGenres = novel.genres || []
return (
<div className="mx-auto max-w-6xl px-4 py-6">
@@ -222,7 +239,7 @@ export default async function NovelDetailPage({
{/* Description */}
<section className="mt-8">
<h2 className="mb-3 text-lg font-bold text-foreground">Giới Thiệu</h2>
<div className="text-sm leading-relaxed text-foreground/80 whitespace-pre-wrap">{novel.description}</div>
<div className="text-sm leading-relaxed text-foreground/80 whitespace-pre-wrap">{novel.description || ""}</div>
</section>
{/* Chapter list or series volumes */}