CoastalCommitsPastes/client/pages/api/render-markdown.ts

44 lines
891 B
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 { content, title } = req.body
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 = content || ""
2022-03-23 18:42:22 -04:00
if (!renderAsMarkdown.includes(type)) {
contentToRender = `~~~${type}
${content}
~~~`
2022-03-23 18:42:22 -04:00
} else {
contentToRender = "\n" + content
}
2022-03-23 18:42:22 -04:00
if (typeof contentToRender !== "string") {
res.status(400).send("content must be a string")
return
}
res.status(200).write(markdown(contentToRender))
res.end()
}
export default renderMarkdown