From a61f2c00e2a47edac8812dc68feafe9d498c2fe5 Mon Sep 17 00:00:00 2001 From: Max Leiter Date: Thu, 24 Mar 2022 18:24:09 -0700 Subject: [PATCH] client: proxy html render requests so they can be cached easier --- client/components/preview/index.tsx | 2 +- client/pages/api/html/[id].ts | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 client/pages/api/html/[id].ts diff --git a/client/components/preview/index.tsx b/client/components/preview/index.tsx index 2b817b6a..3180a53a 100644 --- a/client/components/preview/index.tsx +++ b/client/components/preview/index.tsx @@ -15,7 +15,7 @@ const MarkdownPreview = ({ height = 500, fileId, content, title }: Props) => { useEffect(() => { async function fetchPost() { if (fileId) { - const resp = await fetch(`/server-api/files/html/${fileId}`, { + const resp = await fetch(`/api/html/${fileId}`, { method: "GET", }) if (resp.ok) { diff --git a/client/pages/api/html/[id].ts b/client/pages/api/html/[id].ts new file mode 100644 index 00000000..8638e6d9 --- /dev/null +++ b/client/pages/api/html/[id].ts @@ -0,0 +1,24 @@ +import { NextApiRequest, NextApiResponse } from "next" + +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"]}` + } + }) + 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") + } +} + +export default getRawFile