2022-11-14 02:02:31 -05:00
|
|
|
import { withMethods } from "@lib/api-middleware/with-methods"
|
|
|
|
import { parseQueryParam } from "@lib/server/parse-query-param"
|
2022-12-04 04:55:20 -05:00
|
|
|
import { PostWithFiles, searchPosts } from "@lib/server/prisma"
|
2022-11-14 02:02:31 -05:00
|
|
|
import { NextApiRequest, NextApiResponse } from "next"
|
2022-12-04 04:55:20 -05:00
|
|
|
import { getSession } from "next-auth/react"
|
2022-11-14 02:02:31 -05:00
|
|
|
|
|
|
|
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
|
|
|
const { q, userId } = req.query
|
|
|
|
|
2022-12-04 04:55:20 -05:00
|
|
|
const session = await getSession()
|
|
|
|
|
2022-11-14 02:02:31 -05:00
|
|
|
const query = parseQueryParam(q)
|
|
|
|
if (!query) {
|
|
|
|
res.status(400).json({ error: "Invalid query" })
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2022-12-04 04:55:20 -05:00
|
|
|
let posts: PostWithFiles[]
|
|
|
|
if (session?.user.id === userId || session?.user.role === "admin") {
|
|
|
|
posts = await searchPosts(query, {
|
|
|
|
userId: parseQueryParam(userId),
|
|
|
|
publicOnly: true
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
posts = await searchPosts(query, {
|
|
|
|
userId: parseQueryParam(userId),
|
|
|
|
publicOnly: true
|
|
|
|
})
|
|
|
|
}
|
2022-11-14 02:02:31 -05:00
|
|
|
|
|
|
|
res.status(200).json(posts)
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err)
|
|
|
|
res.status(500).json({ error: "Internal server error" })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default withMethods(["GET"], handler)
|