mirror of https://github.com/MaxLeiter/Drift
migrate post page and create post api, misc changes
parent
60d1b031f5
commit
96c4023c14
@ -1,81 +0,0 @@
|
||||
import type { GetServerSideProps } from "next"
|
||||
|
||||
import type { Post } from "@lib/types"
|
||||
import PostPage from "@components/post-page"
|
||||
import { USER_COOKIE_NAME } from "@lib/constants"
|
||||
|
||||
export type PostProps = {
|
||||
post: Post
|
||||
isProtected?: boolean
|
||||
}
|
||||
|
||||
const PostView = ({ post, isProtected }: PostProps) => {
|
||||
return <PostPage isProtected={isProtected} post={post} />
|
||||
}
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = async ({
|
||||
params,
|
||||
req,
|
||||
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"]}`
|
||||
}
|
||||
})
|
||||
|
||||
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) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: "/404",
|
||||
permanent: false
|
||||
},
|
||||
props: {}
|
||||
}
|
||||
}
|
||||
|
||||
const json = (await post.json()) as Post
|
||||
const isAuthor = json.users?.find(
|
||||
(user) => user.id === req.cookies[USER_COOKIE_NAME]
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
props: {
|
||||
post: json,
|
||||
key: params?.id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default PostView
|
||||
@ -0,0 +1,136 @@
|
||||
import type { GetServerSideProps } from "next"
|
||||
|
||||
import type { Post } from "@lib/types"
|
||||
import PostPage from "@components/post-page"
|
||||
import { USER_COOKIE_NAME } from "@lib/constants"
|
||||
import { notFound } from "next/navigation"
|
||||
import { getPostById } from "@lib/server/prisma"
|
||||
import { getCurrentUser, getSession } from "@lib/server/session"
|
||||
import Header from "@components/header"
|
||||
|
||||
export type PostProps = {
|
||||
post: Post
|
||||
isProtected?: boolean
|
||||
}
|
||||
|
||||
const getPost = async (id: string) => {
|
||||
const post = await getPostById(id, true)
|
||||
const user = await getCurrentUser()
|
||||
|
||||
if (!post) {
|
||||
return notFound()
|
||||
}
|
||||
|
||||
const isAuthor = user?.id === post?.authorId
|
||||
|
||||
if (post.visibility === "public") {
|
||||
return { post, isAuthor, signedIn: Boolean(user) }
|
||||
}
|
||||
|
||||
// must be authed to see unlisted/private
|
||||
if (
|
||||
(post.visibility === "unlisted" || post.visibility === "private") &&
|
||||
!user
|
||||
) {
|
||||
return notFound()
|
||||
}
|
||||
|
||||
if (post.visibility === "private" && !isAuthor) {
|
||||
return notFound()
|
||||
}
|
||||
|
||||
if (post.visibility === "protected" && !isAuthor) {
|
||||
return {
|
||||
post,
|
||||
isProtected: true,
|
||||
isAuthor,
|
||||
signedIn: Boolean(user)
|
||||
}
|
||||
}
|
||||
|
||||
return { post, isAuthor, signedIn: Boolean(user) }
|
||||
}
|
||||
|
||||
const PostView = async ({
|
||||
params
|
||||
}: {
|
||||
params: {
|
||||
id: string,
|
||||
signedIn?: boolean
|
||||
}
|
||||
}) => {
|
||||
const { post, isProtected, isAuthor } = await getPost(params.id)
|
||||
return (
|
||||
<>
|
||||
<Header signedIn />
|
||||
<PostPage isAuthor={isAuthor} isProtected={isProtected} post={post} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// export const getServerSideProps: GetServerSideProps = async ({
|
||||
// params,
|
||||
// req,
|
||||
// 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"]}`
|
||||
// }
|
||||
// })
|
||||
|
||||
// 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) {
|
||||
// return {
|
||||
// redirect: {
|
||||
// destination: "/404",
|
||||
// permanent: false
|
||||
// },
|
||||
// props: {}
|
||||
// }
|
||||
// }
|
||||
|
||||
// const json = (await post.json()) as Post
|
||||
// const isAuthor = json.users?.find(
|
||||
// (user) => user.id === req.cookies[USER_COOKIE_NAME]
|
||||
// )
|
||||
|
||||
// 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
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// return {
|
||||
// props: {
|
||||
// post: json,
|
||||
// key: params?.id
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
export default PostView
|
||||
@ -0,0 +1,13 @@
|
||||
// https://github.com/shadcn/taxonomy/
|
||||
|
||||
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next"
|
||||
|
||||
export function withMethods(methods: string[], handler: NextApiHandler) {
|
||||
return async function (req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.method || !methods.includes(req.method)) {
|
||||
return res.status(405).end()
|
||||
}
|
||||
|
||||
return handler(req, res)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,41 @@
|
||||
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next"
|
||||
import * as z from "zod"
|
||||
import type { ZodSchema, ZodType } from "zod"
|
||||
|
||||
type NextApiRequestWithParsedBody<T> = NextApiRequest & {
|
||||
parsedBody?: T
|
||||
}
|
||||
|
||||
export type NextApiHandlerWithParsedBody<T> = (
|
||||
req: NextApiRequestWithParsedBody<T>,
|
||||
res: NextApiResponse
|
||||
) => ReturnType<NextApiHandler>
|
||||
|
||||
export function withValidation<T extends ZodSchema>(
|
||||
schema: T,
|
||||
handler: NextApiHandler
|
||||
): (
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) => Promise<void | NextApiResponse<any> | NextApiHandlerWithParsedBody<T>> {
|
||||
return async function (req: NextApiRequest, res: NextApiResponse) {
|
||||
try {
|
||||
const body = req.body
|
||||
|
||||
await schema.parseAsync(body)
|
||||
|
||||
;(req as NextApiRequestWithParsedBody<T>).parsedBody = body
|
||||
|
||||
return handler(req, res) as Promise<NextApiHandlerWithParsedBody<T>>
|
||||
} catch (error) {
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
console.error(error)
|
||||
}
|
||||
if (error instanceof z.ZodError) {
|
||||
return res.status(422).json(error.issues)
|
||||
}
|
||||
|
||||
return res.status(422).end()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const CreatePostSchema = z.object({
|
||||
title: z.string(),
|
||||
description: z.string(),
|
||||
files: z.array(z.object({
|
||||
title: z.string(),
|
||||
content: z.string(),
|
||||
})),
|
||||
visibility: z.string(),
|
||||
password: z.string().optional(),
|
||||
expiresAt: z.number().optional().nullish(),
|
||||
parentId: z.string().optional()
|
||||
})
|
||||
|
||||
export const DeletePostSchema = z.object({
|
||||
id: z.string()
|
||||
})
|
||||
@ -1,52 +1,47 @@
|
||||
import { withMethods } from "@lib/api-middleware/with-methods"
|
||||
import { getHtmlFromFile } from "@lib/server/get-html-from-drift-file"
|
||||
import { parseQueryParam } from "@lib/server/parse-query-param"
|
||||
import prisma from "@lib/server/prisma"
|
||||
import { NextApiRequest, NextApiResponse } from "next"
|
||||
|
||||
export default async function handler(
|
||||
export default withMethods(["GET"], (
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
switch (req.method) {
|
||||
case "GET":
|
||||
const query = req.query
|
||||
const fileId = parseQueryParam(query.fileId)
|
||||
const content = parseQueryParam(query.content)
|
||||
const title = parseQueryParam(query.title)
|
||||
) => {
|
||||
const query = req.query
|
||||
const fileId = parseQueryParam(query.fileId)
|
||||
const content = parseQueryParam(query.content)
|
||||
const title = parseQueryParam(query.title)
|
||||
|
||||
if (fileId && (content || title)) {
|
||||
return res.status(400).json({ error: "Too many arguments" })
|
||||
}
|
||||
if (fileId && (content || title)) {
|
||||
return res.status(400).json({ error: "Too many arguments" })
|
||||
}
|
||||
|
||||
if (fileId) {
|
||||
// TODO: abstract to getFileById
|
||||
const file = await prisma.file.findUnique({
|
||||
where: {
|
||||
id: fileId
|
||||
}
|
||||
})
|
||||
if (fileId) {
|
||||
const file = await prisma.file.findUnique({
|
||||
where: {
|
||||
id: fileId
|
||||
}
|
||||
})
|
||||
|
||||
if (!file) {
|
||||
return res.status(404).json({ error: "File not found" })
|
||||
}
|
||||
if (!file) {
|
||||
return res.status(404).json({ error: "File not found" })
|
||||
}
|
||||
|
||||
return res.json(file.html)
|
||||
} else {
|
||||
if (!content || !title) {
|
||||
return res.status(400).json({ error: "Missing arguments" })
|
||||
}
|
||||
return res.json(file.html)
|
||||
} else {
|
||||
if (!content || !title) {
|
||||
return res.status(400).json({ error: "Missing arguments" })
|
||||
}
|
||||
|
||||
const renderedHTML = getHtmlFromFile({
|
||||
title,
|
||||
content
|
||||
})
|
||||
const renderedHTML = getHtmlFromFile({
|
||||
title,
|
||||
content
|
||||
})
|
||||
|
||||
res.setHeader("Content-Type", "text/plain")
|
||||
res.status(200).write(renderedHTML)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
default:
|
||||
return res.status(405).json({ error: "Method not allowed" })
|
||||
res.setHeader("Content-Type", "text/plain")
|
||||
res.status(200).write(renderedHTML)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,24 +1,22 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next"
|
||||
import prisma from "lib/server/prisma"
|
||||
import { parseQueryParam } from "@lib/server/parse-query-param"
|
||||
|
||||
const getRawFile = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const { id } = req.query
|
||||
const file = await fetch(`${process.env.API_URL}/files/html/${id}`, {
|
||||
headers: {
|
||||
"x-secret-key": process.env.SECRET_KEY || "",
|
||||
Authorization: `Bearer ${req.cookies["drift-token"]}`
|
||||
const file = await prisma.file.findUnique({
|
||||
where: {
|
||||
id: parseQueryParam(req.query.id)
|
||||
}
|
||||
})
|
||||
if (file.ok) {
|
||||
const json = await file.text()
|
||||
const data = json
|
||||
// serve the file raw as plain text
|
||||
res.setHeader("Content-Type", "text/plain; charset=utf-8")
|
||||
res.setHeader("Cache-Control", "s-maxage=86400")
|
||||
res.status(200).write(data, "utf-8")
|
||||
res.end()
|
||||
} else {
|
||||
res.status(404).send("File not found")
|
||||
|
||||
if (!file) {
|
||||
return res.status(404).end()
|
||||
}
|
||||
|
||||
res.setHeader("Content-Type", "text/plain")
|
||||
res.setHeader("Cache-Control", "public, max-age=4800")
|
||||
console.log(file.html)
|
||||
return res.status(200).write(file.html)
|
||||
}
|
||||
|
||||
export default getRawFile
|
||||
|
||||
@ -0,0 +1,136 @@
|
||||
// nextjs typescript api handler
|
||||
|
||||
import { withCurrentUser } from "@lib/api-middleware/with-current-user"
|
||||
import { withMethods } from "@lib/api-middleware/with-methods"
|
||||
import {
|
||||
NextApiHandlerWithParsedBody,
|
||||
withValidation
|
||||
} from "@lib/api-middleware/with-validation"
|
||||
import { authOptions } from "@lib/server/auth"
|
||||
import { CreatePostSchema } from "@lib/validations/post"
|
||||
import { Post } from "@prisma/client"
|
||||
import prisma, { getPostById } from "lib/server/prisma"
|
||||
import { NextApiRequest, NextApiResponse } from "next"
|
||||
import { unstable_getServerSession } from "next-auth/next"
|
||||
import { File } from "lib/server/prisma"
|
||||
import * as crypto from "crypto"
|
||||
import { getHtmlFromFile } from "@lib/server/get-html-from-drift-file"
|
||||
import { getSession } from "next-auth/react"
|
||||
import { parseQueryParam } from "@lib/server/parse-query-param"
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
if (req.method === "POST") {
|
||||
return await handlePost(req, res)
|
||||
} else {
|
||||
return await handleGet(req, res)
|
||||
}
|
||||
}
|
||||
|
||||
export default withMethods(["POST", "GET"], handler)
|
||||
|
||||
async function handlePost(req: NextApiRequest, res: NextApiResponse<any>) {
|
||||
try {
|
||||
const session = await unstable_getServerSession(req, res, authOptions)
|
||||
|
||||
const files = req.body.files as File[]
|
||||
const fileTitles = files.map((file) => file.title)
|
||||
const missingTitles = fileTitles.filter((title) => title === "")
|
||||
if (missingTitles.length > 0) {
|
||||
throw new Error("All files must have a title")
|
||||
}
|
||||
|
||||
if (files.length === 0) {
|
||||
throw new Error("You must submit at least one file")
|
||||
}
|
||||
|
||||
let hashedPassword: string = ""
|
||||
if (req.body.visibility === "protected") {
|
||||
hashedPassword = crypto
|
||||
.createHash("sha256")
|
||||
.update(req.body.password)
|
||||
.digest("hex")
|
||||
}
|
||||
|
||||
const postFiles = files.map((file) => {
|
||||
const html = getHtmlFromFile(file)
|
||||
|
||||
return {
|
||||
title: file.title,
|
||||
content: file.content,
|
||||
sha: crypto
|
||||
.createHash("sha256")
|
||||
.update(file.content)
|
||||
.digest("hex")
|
||||
.toString(),
|
||||
html: html,
|
||||
userId: session?.user.id
|
||||
// postId: post.id
|
||||
}
|
||||
}) as File[]
|
||||
|
||||
const post = await prisma.post.create({
|
||||
data: {
|
||||
title: req.body.title,
|
||||
description: req.body.description,
|
||||
visibility: req.body.visibility,
|
||||
password: hashedPassword,
|
||||
expiresAt: req.body.expiresAt,
|
||||
// authorId: session?.user.id,
|
||||
author: {
|
||||
connect: {
|
||||
id: session?.user.id
|
||||
}
|
||||
},
|
||||
files: {
|
||||
create: postFiles
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return res.json(post)
|
||||
} catch (error) {
|
||||
return res.status(500).json(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGet(req: NextApiRequest, res: NextApiResponse<any>) {
|
||||
const id = parseQueryParam(req.query.id)
|
||||
const files = req.query.files ? parseQueryParam(req.query.files) : true
|
||||
|
||||
if (!id) {
|
||||
return res.status(400).json({ error: "Missing id" })
|
||||
}
|
||||
|
||||
const post = await getPostById(id, Boolean(files))
|
||||
|
||||
if (!post) {
|
||||
return res.status(404).json({ message: "Post not found" })
|
||||
}
|
||||
|
||||
if (post.visibility === "public") {
|
||||
res.setHeader("Cache-Control", "s-maxage=86400, stale-while-revalidate")
|
||||
return res.json(post)
|
||||
} else if (post.visibility === "unlisted") {
|
||||
res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate")
|
||||
}
|
||||
|
||||
const session = await getSession({ req })
|
||||
|
||||
// the user can always go directly to their own post
|
||||
if (session?.user.id === post.authorId) {
|
||||
return res.json(post)
|
||||
}
|
||||
|
||||
if (post.visibility === "protected") {
|
||||
return {
|
||||
isProtected: true,
|
||||
post: {
|
||||
id: post.id,
|
||||
visibility: post.visibility,
|
||||
title: post.title
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res.status(404).json({ message: "Post not found" })
|
||||
}
|
||||
Loading…
Reference in New Issue