CoastalCommitsPastes/client/pages/post/[id].tsx

78 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-04-09 20:48:19 -04:00
import type { GetServerSideProps, GetStaticPaths, GetStaticProps } from "next"
2022-03-07 23:42:44 -05:00
2022-04-09 20:48:19 -04:00
import type { Post } from "@lib/types"
import PostPage from "@components/post-page"
2022-03-06 19:46:59 -05:00
export type PostProps = {
2022-04-09 20:48:19 -04:00
post: Post
isProtected?: boolean
}
2022-03-07 01:16:08 -05:00
const PostView = ({ post, isProtected }: PostProps) => {
return <PostPage isProtected={isProtected} post={post} />
2022-03-06 19:46:59 -05:00
}
2022-04-09 20:48:19 -04:00
export const getServerSideProps: GetServerSideProps = async ({
params,
req,
2022-04-09 20:48:19 -04:00
res
}) => {
const post = await fetch(process.env.API_URL + `/posts/${params?.id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"x-secret-key": process.env.SECRET_KEY || "",
Authorization: `Bearer ${req.cookies["drift-token"]}`
2022-04-09 20:48:19 -04:00
}
})
if (post.status === 401 || post.status === 403) {
return {
// can't access the post if it's private
redirect: {
destination: "/",
permanent: false
},
props: {}
}
} else if (post.status === 404 || !post.ok) {
2022-04-09 20:48:19 -04:00
return {
redirect: {
destination: "/404",
permanent: false
},
props: {}
}
}
const json = await post.json() as Post
const isAuthor = json.users?.find(user => user.id === req.cookies["drift-userid"])
if (json.visibility === "public" || json.visibility === "unlisted") {
const sMaxAge = 60 * 60 * 12 // half a day
res.setHeader(
"Cache-Control",
`public, s-maxage=${sMaxAge}, max-age=${sMaxAge}`
)
} else if (json.visibility === "protected" && !isAuthor) {
return {
props: {
post: {
id: json.id,
visibility: json.visibility,
expiresAt: json.expiresAt,
},
isProtected: true
}
}
}
2022-04-09 20:48:19 -04:00
return {
props: {
post: json
}
}
2022-03-06 19:46:59 -05:00
}
export default PostView