CoastalCommitsPastes/client/pages/api/markdown/[id].ts

59 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-03-23 18:34:23 -04:00
import type { NextApiHandler } from "next"
2022-03-23 18:34:23 -04:00
import markdown from "@lib/render-markdown"
const renderMarkdown: NextApiHandler = async (req, res) => {
2022-03-23 18:42:22 -04:00
const { id } = req.query
const file = await fetch(`${process.env.API_URL}/files/raw/${id}`, {
headers: {
Accept: "text/plain",
"x-secret-key": process.env.SECRET_KEY || "",
Authorization: `Bearer ${req.cookies["drift-token"]}`
}
})
console.log(file.status)
if (file.status !== 200) {
return res.status(404).json({ error: "File not found" })
}
2022-03-23 18:34:23 -04:00
2022-03-23 18:42:22 -04:00
const json = await file.json()
const { content, title } = json
const renderAsMarkdown = [
"markdown",
"md",
"mdown",
"mkdn",
"mkd",
"mdwn",
"mdtxt",
"mdtext",
"text",
""
]
const fileType = () => {
const pathParts = title.split(".")
const language = pathParts.length > 1 ? pathParts[pathParts.length - 1] : ""
return language
}
const type = fileType()
let contentToRender: string = "\n" + content
2022-03-23 18:42:22 -04:00
if (!renderAsMarkdown.includes(type)) {
contentToRender = `~~~${type}
${content}
~~~`
2022-03-23 18:42:22 -04:00
}
2022-03-23 18:42:22 -04:00
if (typeof contentToRender !== "string") {
res.status(400).send("content must be a string")
return
}
2022-03-23 18:42:22 -04:00
res.setHeader("Content-Type", "text/plain")
res.setHeader("Cache-Control", "public, max-age=4800")
res.status(200).write(markdown(contentToRender))
res.end()
}
export default renderMarkdown