Skip to content

Commit

Permalink
refactor(viewer): simplify specific db queries
Browse files Browse the repository at this point in the history
- Simplify and optimize **certain** database queries in 'viewer' module.
- **Husky was disabled, ESLint not passed. Not ready for production use yet.**
  • Loading branch information
immccn123 committed Sep 27, 2023
1 parent 6326fb4 commit 3858e9e
Show file tree
Hide file tree
Showing 23 changed files with 243 additions and 122 deletions.
Empty file added notice.md
Empty file.
4 changes: 2 additions & 2 deletions packages/viewer/src/app/(indices)/DiscussionIndex.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import stringifyTime from "@/lib/time";
import type { Discussion } from "@/lib/discussion";
import type { PostWithLatestSnapshotMeta } from "@/lib/post";
import DiscussionEntry from "@/components/DiscussionEntry";

export default function DiscussionIndex({
discussions,
}: {
discussions: Discussion[];
discussions: PostWithLatestSnapshotMeta[];
}) {
return (
<>
Expand Down
6 changes: 3 additions & 3 deletions packages/viewer/src/app/(indices)/index/[page]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import prisma from "@/lib/prisma";
import { selectDiscussion } from "@/lib/discussion";
import { getPost } from "@/lib/post";
import { NUM_DISCUSSIONS_INDEX } from "../../constants";
import DiscussionIndex from "../../DiscussionIndex";

export const metadata = { title: "索引 - 洛谷帖子保存站" };

export default async function Page({ params }: { params: { page: string } }) {
const page = parseInt(params.page, 10);
const discussions = await prisma.discussion.findMany({
select: selectDiscussion,
const discussions = await prisma.post.findMany({
select: getPost.latestNoContent,
where: { takedown: { is: null } },
orderBy: { id: "desc" },
skip: (page - 1) * NUM_DISCUSSIONS_INDEX,
Expand Down
6 changes: 3 additions & 3 deletions packages/viewer/src/app/(indices)/popular/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import prisma from "@/lib/prisma";
import { selectDiscussion } from "@/lib/discussion";
import { getPost } from "@/lib/post";
import { NUM_DISCUSSIONS_INDEX } from "../constants";
import DiscussionIndex from "../DiscussionIndex";

Expand All @@ -12,11 +12,11 @@ export default async function MostReplied() {
<>
<h3 className="pb-1 text-center mb-4s">最多回复</h3>
<DiscussionIndex
discussions={await prisma.discussion.findMany({
select: selectDiscussion,
discussions={await prisma.post.findMany({
where: { takedown: { is: null } },
orderBy: { replyCount: "desc" },
take: NUM_DISCUSSIONS_INDEX,
select: getPost.latestNoContent,
})}
/>
</>
Expand Down
2 changes: 1 addition & 1 deletion packages/viewer/src/app/[id]/[page]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default async function Page({
snapshots: [{ authorId }],
replies,
_count: { replies: numReplies },
} = await prisma.discussion
} = await prisma.post
.findUnique({
where: { id },
select: {
Expand Down
2 changes: 1 addition & 1 deletion packages/viewer/src/app/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default async function Page({ params }: { params: { id: string } }) {
snapshots: [{ authorId }],
_count: { replies },
} =
(await prisma.discussion.findUnique({
(await prisma.post.findUnique({
where: { id },
select: {
snapshots: {
Expand Down
23 changes: 6 additions & 17 deletions packages/viewer/src/app/[id]/replies/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import serializeReply from "@/lib/serialize-reply";

import { selectReply } from "@/lib/reply";

export async function GET(
request: NextRequest,
{ params }: { params: { id: string } },
Expand All @@ -11,25 +13,12 @@ export async function GET(
const limit = request.nextUrl.searchParams.get("limit");
const replies = await prisma.reply.findMany({
select: {
id: true,
author: true,
time: true,
content: true,
discussionId: true,
takedown: {
select: {
submitter: {
select: {
id: true,
username: true,
},
},
reason: true,
},
},
...selectReply.withBasic,
...selectReply.withTakedown,
...selectReply.withLatestContent,
},
where: {
discussionId: id,
postId: id,
id: { gt: cursor ? parseInt(cursor, 10) : undefined },
},
take: parseInt(limit ?? "10", 10),
Expand Down
16 changes: 8 additions & 8 deletions packages/viewer/src/app/explore/Discussions.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import prisma from "@/lib/prisma";
import stringifyTime from "@/lib/time";
import { selectDiscussion } from "@/lib/discussion";
import { getPost } from "@/lib/post";
import DiscussionEntry from "@/components/DiscussionEntry";

const NUM_DISCUSSIONS_HOME_PAGE = parseInt(
Expand All @@ -14,33 +14,33 @@ const LIMIT_MILLISECONDS_HOT_DISCUSSION = parseInt(

export default async function Discussions() {
const discussionReplyCount = await prisma.reply.groupBy({
by: ["discussionId"],
by: ["postId"],
where: {
time: {
gte: new Date(new Date().getTime() - LIMIT_MILLISECONDS_HOT_DISCUSSION),
},
discussion: { takedown: { is: null } },
post: { takedown: { is: null } },
},
_count: true,
orderBy: { _count: { id: "desc" } },
take: NUM_DISCUSSIONS_HOME_PAGE,
});
const discussions = Object.fromEntries(
(
await prisma.discussion.findMany({
select: selectDiscussion,
where: { id: { in: discussionReplyCount.map((r) => r.discussionId) } },
await prisma.post.findMany({
select: getPost.latestNoContent,
where: { id: { in: discussionReplyCount.map((r) => r.postId) } },
})
).map((d) => [d.id, d]),
);
discussionReplyCount.map((r) => ({
...discussions[r.discussionId],
...discussions[r.postId],
recentReplyCount: r._count,
}));

return discussionReplyCount
.map((r) => ({
...discussions[r.discussionId],
...discussions[r.postId],
recentReplyCount: r._count,
}))
.map((discussion) => (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

import useSWRInfinite from "swr/infinite";
import InfiniteScroll from "react-infinite-scroll-component";
import type { DiscussionWithContent } from "@/lib/discussion";
import type { PostWithLatestContent } from "@/lib/post";
import type { UserMetioned } from "@/lib/serialize-reply";
import Content from "@/components/replies/Content";
import fetcher from "@/lib/fetcher";
import Spinner from "@/components/Spinner";
import DiscussionEntry from "@/components/DiscussionEntry";

interface PageData {
data: (DiscussionWithContent & {
data: (PostWithLatestContent & {
content: string;
time: string;
usersMetioned: UserMetioned[];
Expand Down
20 changes: 9 additions & 11 deletions packages/viewer/src/app/user/[uid]/discussions/data/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NextResponse, type NextRequest } from "next/server";
import prisma from "@/lib/prisma";
import { selectDiscussionWithContent } from "@/lib/discussion";
import { getPost } from "@/lib/post";
import serializeReply from "@/lib/serialize-reply";
import { NUM_PER_PAGE } from "../../constants";

Expand All @@ -10,8 +10,8 @@ export async function GET(
) {
const uid = parseInt(params.uid, 10);
const cursor = request.nextUrl.searchParams.get("cursor");
const discussions = await prisma.discussion.findMany({
select: selectDiscussionWithContent,
const posts = await prisma.post.findMany({
select: getPost.latestWithContent,
where: {
snapshots: { some: { authorId: uid } },
takedown: { is: null },
Expand All @@ -22,16 +22,14 @@ export async function GET(
});
return NextResponse.json({
data: await Promise.all(
discussions.map(async (discussion) => ({
...discussion,
...(await serializeReply(discussion.id, {
content: discussion.snapshots[0].content,
time: discussion.time,
posts.map(async (post) => ({
...post,
...(await serializeReply(post.id, {
content: post.snapshots[0].content,
time: post.time,
})),
})),
),
nextCursor: discussions.length
? discussions[discussions.length - 1].id
: null,
nextCursor: posts.length ? posts[posts.length - 1].id : null,
});
}
11 changes: 6 additions & 5 deletions packages/viewer/src/app/user/[uid]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ export async function generateMetadata({
}: {
params: { uid: string };
}) {
const { username } =
(await prisma.user.findUnique({
select: { username: true },
where: { id: parseInt(params.uid, 10) },
const uid = parseInt(params.uid, 10);
const { name } =
(await prisma.userSnapshot.findFirst({
where: { userId: uid },
orderBy: { time: "desc" },
})) ?? notFound();
return { title: `@${username} 的黑历史 - 洛谷帖子保存站` };
return { title: `@${name} 的黑历史 - 洛谷帖子保存站` };
}

export default async function Layout({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Link from "next/link";
import useSWRInfinite from "swr/infinite";
import InfiniteScroll from "react-infinite-scroll-component";
import type { User } from "@prisma/client";
import type { DiscussionWithContent } from "@/lib/discussion";
import type { PostWithLatestContent } from "@/lib/post";
import type { UserMetioned } from "@/lib/serialize-reply";
import UserAvatar from "@/components/UserAvatar";
import UserInfo from "@/components/UserInfo";
Expand All @@ -14,7 +14,7 @@ import Spinner from "@/components/Spinner";
import { NUM_MAX_REPLIES_SHOWED_DEFAULT } from "../constants";

interface PageData {
data: (DiscussionWithContent & {
data: (PostWithLatestContent & {
content: string;
time: string;
usersMetioned: UserMetioned[];
Expand Down
17 changes: 12 additions & 5 deletions packages/viewer/src/app/user/[uid]/participated/data/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { NextResponse, type NextRequest } from "next/server";
import prisma from "@/lib/prisma";
import { selectDiscussionWithContent } from "@/lib/discussion";
import { getPost } from "@/lib/post";
import serializeReply from "@/lib/serialize-reply";
import { getReply } from "@/lib/reply";
import { NUM_PER_PAGE } from "../../constants";

export async function GET(
Expand All @@ -10,15 +11,21 @@ export async function GET(
) {
const uid = parseInt(params.uid, 10);
const cursor = request.nextUrl.searchParams.get("cursor");
const discussions = await prisma.discussion
const discussions = await prisma.post
.findMany({
select: {
...selectDiscussionWithContent,
replies: { where: { authorId: uid }, orderBy: { id: "asc" } },
...getPost.latestWithContent,
replies: {
where: {
snapshots: { some: { authorId: uid } },
},
select: getReply.latestWithContent,
orderBy: { id: "asc" },
},
},
where: {
OR: [
{ replies: { some: { authorId: uid } } },
{ replies: { some: { snapshots: { some: { authorId: uid } } } } },
{ snapshots: { some: { authorId: uid } } },
],
takedown: { is: null },
Expand Down
29 changes: 13 additions & 16 deletions packages/viewer/src/app/user/[uid]/replies/data/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { NextResponse, type NextRequest } from "next/server";
import { getPost } from "@/lib/post";
import { getReply } from "@/lib/reply";
import prisma from "@/lib/prisma";
import serializeReply from "@/lib/serialize-reply";
import { NUM_PER_PAGE } from "../../constants";
Expand All @@ -12,33 +14,28 @@ export async function GET(
const replies = await prisma.reply
.findMany({
select: {
id: true,
time: true,
author: true,
content: true,
discussion: {
select: {
id: true,
snapshots: {
select: { title: true, authorId: true },
orderBy: { time: "desc" },
take: 1,
},
},
...getReply.latestWithContent,
post: {
select: getPost.latestNoContent,
},
},
where: {
authorId: uid,
discussion: { takedown: { is: null } },
post: { takedown: { is: null } },
takedown: { is: null },
id: { lt: cursor ? parseInt(cursor, 10) : undefined },
snapshots: {
some: {
authorId: uid,
},
},
},
orderBy: { id: "desc" },
take: NUM_PER_PAGE,
})
.then((r) =>
r.map(async (reply) => ({
...reply,
...(await serializeReply(reply.discussion.id, reply)),
...(await serializeReply(reply.post.id, reply.snapshots[0])),
})),
)
.then((r) => Promise.all(r));
Expand Down
4 changes: 2 additions & 2 deletions packages/viewer/src/app/user/[uid]/statistics/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ export async function GET(
) {
const uid = parseInt(params.uid, 10);
const [discussions, replies, judgements] = await Promise.all([
prisma.discussion.count({
prisma.post.count({
where: { snapshots: { some: { authorId: uid } } },
}),
prisma.reply.count({ where: { authorId: uid } }),
prisma.reply.count({ where: { snapshots: { some: { authorId: uid } } } }),
prisma.judgement.count({ where: { userId: uid } }),
]);
return NextResponse.json({ discussions, replies, judgements });
Expand Down
4 changes: 2 additions & 2 deletions packages/viewer/src/components/DiscussionEntry.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Link from "next/link";
import { ReactNode } from "react";
import type { Discussion } from "@/lib/discussion";
import type { PostWithLatestSnapshotMeta } from "@/lib/post";
import UserAvatar from "./UserAvatar";
import UserInfo from "./UserInfo";

Expand All @@ -12,7 +12,7 @@ export default function DiscussionEntry({
metaBottom,
children,
}: React.PropsWithChildren<{
discussion: Discussion;
discussion: PostWithLatestSnapshotMeta;
// eslint-disable-next-line react/require-default-props
decoratorShadow?: string;
decoratorBreakpoint?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/viewer/src/components/Ostracon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export default function Ostracon({
{/* eslint-disable-next-line react/no-danger */}
<div dangerouslySetInnerHTML={{ __html: ostracon.content }} />
<span className="text-body-tertiary">
{/* TODO: icon font instead of svg */}
<svg
xmlns="http://www.w3.org/2000/svg"
width="1em"
Expand Down
Empty file.
1 change: 1 addition & 0 deletions packages/viewer/src/components/replies/Reply.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export default function Reply({
className="ms-2 link-secondary position-relative"
style={{ fontSize: ".8em", top: "-.2em" }}
>
{/* TODO: svg to iconfont */}
<svg
xmlns="http://www.w3.org/2000/svg"
width="1em"
Expand Down
Loading

0 comments on commit 3858e9e

Please sign in to comment.