2022-03-22 20:37:21 -04:00
|
|
|
import type { NextApiHandler } from "next";
|
|
|
|
|
|
|
|
import markdown from "@lib/render-markdown";
|
|
|
|
|
|
|
|
const renderMarkdown: NextApiHandler = async (req, res) => {
|
|
|
|
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']}`,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
const json = await file.json()
|
|
|
|
const { content, title } = json
|
2022-03-22 23:06:15 -04:00
|
|
|
const renderAsMarkdown = ['markdown', 'md', 'mdown', 'mkdn', 'mkd', 'mdwn', 'mdtxt', 'mdtext', 'text', '']
|
2022-03-22 20:37:21 -04:00
|
|
|
const fileType = () => {
|
|
|
|
const pathParts = title.split(".")
|
|
|
|
const language = pathParts.length > 1 ? pathParts[pathParts.length - 1] : ""
|
|
|
|
return language
|
|
|
|
}
|
|
|
|
const type = fileType()
|
2022-03-22 23:06:15 -04:00
|
|
|
let contentToRender: string = '\n' + content;
|
2022-03-22 20:37:21 -04:00
|
|
|
|
|
|
|
if (!renderAsMarkdown.includes(type)) {
|
|
|
|
contentToRender = `~~~${type}
|
|
|
|
${content}
|
|
|
|
~~~`
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof contentToRender !== 'string') {
|
|
|
|
res.status(400).send('content must be a string')
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|