From 64cfe9033ef9f04d7067e3d587656340fae6d726 Mon Sep 17 00:00:00 2001 From: Max Leiter Date: Tue, 21 Feb 2023 23:19:55 -0800 Subject: [PATCH] Add (unworking) route handler for raw files --- .../post/[id]/file/raw/[fileId]/route.ts | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/app/(posts)/post/[id]/file/raw/[fileId]/route.ts diff --git a/src/app/(posts)/post/[id]/file/raw/[fileId]/route.ts b/src/app/(posts)/post/[id]/file/raw/[fileId]/route.ts new file mode 100644 index 00000000..acce5581 --- /dev/null +++ b/src/app/(posts)/post/[id]/file/raw/[fileId]/route.ts @@ -0,0 +1,62 @@ +import { parseQueryParam } from "@lib/server/parse-query-param" +import { notFound } from "next/navigation" +import { NextResponse } from "next/server" +import { prisma } from "src/lib/server/prisma" + +export async function GET( + req: Request, + { + params + }: { + params: { + fileId: string + } + } +) { + console.log("GET /api/file/raw/[fileId]/route.ts") + const id = params.fileId + const download = new URL(req.url).searchParams.get("download") === "true" + + if (!id) { + return notFound() + } + + const file = await prisma.file.findUnique({ + where: { + id: parseQueryParam(id) + } + }) + + if (!file) { + return notFound() + } + + const { title, content: contentBuffer } = file + const content = contentBuffer.toString("utf-8") + + console.log("title", title) + let headers: HeadersInit = { + "Content-Type": "text/plain; charset=utf-8", + "Cache-Control": "s-maxage=86400" + } + + if (download) { + headers = { + ...headers, + "Content-Disposition": `attachment; filename="${title}"` + } + } else { + headers = { + ...headers, + "Content-Disposition": `inline; filename="${title}"` + } + } + + // TODO: we need to return the raw content for this to work. not currently implemented in next.js + return NextResponse.json( + { data: content }, + { + headers + } + ) +}