Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 0 additions & 57 deletions app/api/posts/[id]/route.ts

This file was deleted.

81 changes: 45 additions & 36 deletions app/api/posts/route.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { z } from "zod/v4";
import * as z from "zod";
import type { NextRequest } from "next/server";
import { desc, lt, and, or, eq } from "drizzle-orm";
import { revalidateTag, unstable_cache } from "next/cache";

import { db } from "@/db";
import { tagsToPostsTable, postTable } from "@/db/schema";
import { getSession } from "@/lib/auth";
import { aesDecrypt, aesEncrypt } from "@/lib/aes";
import { aesEncrypt } from "@/lib/aes";
import { safeDecrypt } from "@/lib/utils";
import { tagsToPostsTable, postTable } from "@/db/schema";

export async function GET(request: NextRequest) {
try {
Expand All @@ -18,47 +20,52 @@ export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const cursor = searchParams.get("cursor");

let cursorCondition;

if (cursor) {
const [createdAt, cursorId] = cursor.split("_");
const cursorDate = new Date(createdAt);

cursorCondition = or(
lt(postTable.createdAt, cursorDate),
and(eq(postTable.createdAt, cursorDate), lt(postTable.id, cursorId)),
);
}
const posts = await unstable_cache(
async () => {
let cursorCondition;

if (cursor) {
const [createdAt, cursorId] = cursor.split("_");
const cursorDate = new Date(createdAt);

cursorCondition = or(
lt(postTable.createdAt, cursorDate),
and(
eq(postTable.createdAt, cursorDate),
lt(postTable.id, cursorId),
),
);
}

const posts = await db.query.postTable.findMany({
with: {
tagsToPosts: {
const data = await db.query.postTable.findMany({
with: {
tag: true,
tagsToPosts: {
with: {
tag: true,
},
},
},
},
where: cursorCondition
? and(cursorCondition, eq(postTable.forumId, session?.forumId))
: eq(postTable.forumId, session?.forumId),
orderBy: [desc(postTable.createdAt), desc(postTable.id)],
limit: 10,
});

return data;
},
where: and(cursorCondition, eq(postTable.forumId, session?.forumId)),
orderBy: [desc(postTable.createdAt), desc(postTable.id)],
limit: 10,
});
["api-posts", session.forumId, cursor ?? ""],
{
tags: [`posts:${session.forumId}:feed`],
revalidate: 60,
},
)();

const postsData = await Promise.all(
posts.map(async ({ tagsToPosts, ...rest }) => {
let title: string;
let content: string;

try {
title = await aesDecrypt(rest.title);
} catch {
title = rest.title;
}
const title = await safeDecrypt(rest.title);
const content = await safeDecrypt(rest.content);

try {
content = await aesDecrypt(rest.content);
} catch {
content = rest.content;
}
return {
...rest,
title,
Expand Down Expand Up @@ -132,6 +139,8 @@ export async function POST(req: Request) {
});
}

revalidateTag(`posts:${session.forumId}:feed`);

return Response.json(
{ message: "Post added successfully" },
{ status: 200 },
Expand Down
6 changes: 5 additions & 1 deletion app/api/tags/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { db } from "@/db";
import { tagTable } from "@/db/schema";
import { getSession } from "@/lib/auth";
import { eq } from "drizzle-orm";
import { unstable_cache } from "next/cache";
import { NextRequest } from "next/server";
import z from "zod/v4";

Expand All @@ -12,7 +13,10 @@ export async function GET() {
if (!session) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const tags = await db.query.tagTable.findMany();
const tags = await unstable_cache(
async () => db.query.tagTable.findMany(),
["api-tags"],
)();

return Response.json(tags);
} catch (error) {
Expand Down
60 changes: 45 additions & 15 deletions app/posts/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { Metadata } from "next";
import { eq } from "drizzle-orm";
import remarkGfm from "remark-gfm";
import Markdown from "react-markdown";
import { notFound } from "next/navigation";
import { unstable_cache } from "next/cache";

import { Post, Tag } from "@/db/schema";
import { db } from "@/db";
import { postTable } from "@/db/schema";
import { Footer } from "@/components/footer";
import { Badge } from "@/components/ui/badge";
import { PostDate } from "./components/post-date";
import { Separator } from "@/components/ui/separator";
import { ShareButton } from "./components/share-button";
import { getBaseUrl, truncateContent } from "@/lib/utils";
import { safeDecrypt, truncateContent } from "@/lib/utils";
import { ForumNavbar } from "@/app/forum/components/forum-navbar";

type Props = {
Expand All @@ -20,13 +23,13 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { id } = await params;
const post = await getPost(id);

const title = `Umedu – ${post.title}`;
const description = truncateContent(post.content, 160);
const title = `Umedu – ${post?.title}`;
const description = truncateContent(post?.content ?? "", 160);

return {
metadataBase: new URL(`https://umedu.omsimos.com/posts/${id}`),
title: `Umedu | ${post.title}`,
description: truncateContent(post.content),
title: `Umedu | ${post?.title}`,
description: truncateContent(post?.content ?? ""),
openGraph: {
type: "website",
siteName: "Umedu",
Expand All @@ -49,6 +52,10 @@ export default async function Page({ params }: Props) {
const { id } = await params;
const post = await getPost(id);

if (!post) {
notFound();
}

return (
<div className="min-h-screen flex flex-col justify-between">
<div className="mb-8">
Expand Down Expand Up @@ -82,16 +89,39 @@ export default async function Page({ params }: Props) {
);
}

async function getPost(id: string): Promise<Post & { tags: Tag[] }> {
const res = await fetch(`${getBaseUrl()}/api/posts/${id}`, {
cache: "force-cache",
next: {
tags: [`post-${id}`],
async function getPost(id: string) {
const post = await unstable_cache(
async () =>
db.query.postTable.findFirst({
where: eq(postTable.id, id),
with: {
tagsToPosts: {
with: {
tag: true,
},
},
},
}),
[id],
{
tags: [`post:${id}`],
revalidate: 120,
},
});
)();

if (!post) {
return null;
}

const { tagsToPosts, ...rest } = post;

if (!res.ok) notFound();
const post = await res.json();
const title = await safeDecrypt(rest.title);
const content = await safeDecrypt(rest.content);

return post;
return {
...rest,
title,
content,
tags: tagsToPosts.map((t) => t.tag),
};
}
Loading