CoastalCommitsPastes/client/app/(posts)/post/[id]/page.tsx

96 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-11-12 03:58:21 -05:00
import PostPage from "app/(posts)/post/[id]/components/post-page"
import { notFound, redirect } from "next/navigation"
2022-11-30 01:22:17 -05:00
import { getAllPosts, getPostById, Post } from "@lib/server/prisma"
import { getCurrentUser } from "@lib/server/session"
export type PostProps = {
post: Post
isProtected?: boolean
}
export async function generateStaticParams() {
const posts = await getAllPosts({
where: {
visibility: {
equals: "public"
}
}
})
2022-11-12 21:39:03 -05:00
return posts.map((post) => ({
id: post.id
}))
}
2022-11-12 21:39:03 -05:00
const getPost = async (id: string) => {
const post = await getPostById(id, {
withFiles: true,
withAuthor: true
})
2022-11-12 21:39:03 -05:00
if (!post) {
return notFound()
}
if (post.visibility === "public") {
return { post }
}
2022-11-30 01:22:17 -05:00
const user = await getCurrentUser()
const isAuthorOrAdmin = user?.id === post?.authorId || user?.role === "admin"
if (post.visibility === "public") {
return { post, isAuthor: isAuthorOrAdmin }
}
2022-11-18 01:36:53 -05:00
if (post.visibility === "private" && !isAuthorOrAdmin) {
return notFound()
}
if (post.visibility === "private" && !isAuthorOrAdmin) {
return notFound()
}
if (post.visibility === "protected" && !isAuthorOrAdmin) {
return {
post: {
visibility: "protected",
id: post.id
},
isProtected: true,
isAuthor: isAuthorOrAdmin
}
}
// if expired
if (post.expiresAt && !isAuthorOrAdmin) {
const expirationDate = new Date(post.expiresAt)
if (expirationDate < new Date()) {
return redirect("/expired")
}
}
return { post, isAuthor: isAuthorOrAdmin }
}
const PostView = async ({
params
}: {
params: {
2022-11-12 04:28:06 -05:00
id: string
}
}) => {
const { post, isProtected, isAuthor } = await getPost(params.id)
// TODO: serialize dates in prisma middleware instead of passing as JSON
const stringifiedPost = JSON.stringify(post)
return (
<PostPage
isAuthor={isAuthor}
isProtected={isProtected}
post={stringifiedPost}
/>
)
}
export default PostView