Add file handlers, s3 support

This commit is contained in:
2024-12-27 12:46:28 +05:30
parent 88046d6810
commit 40b2ab54f0
11 changed files with 1533 additions and 0 deletions

View File

@@ -0,0 +1,73 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { generateId } from "../utils/id";
import { deleteFileS3, getFileUrlS3, uploadFileS3 } from "../utils/s3";
import { createFile, getFile } from "./file.service";
export async function fileUploadHandler(
req: FastifyRequest,
res: FastifyReply
) {
const file = await req.file();
if (!file) return res.code(400).send({ error: "file not found in the body" });
try {
const chunks = [];
for await (const chunk of file.file) {
chunks.push(Buffer.from(chunk));
}
const fileData = Buffer.concat(chunks);
const key = generateId();
await uploadFileS3(key, fileData);
const fileRec = await createFile(
key,
file.filename,
file.mimetype,
req.user.tenantId
);
return res.code(201).send(fileRec);
} catch (err) {
return err;
}
}
export async function fileDownloadHandler(
req: FastifyRequest,
res: FastifyReply
) {
const { fileId } = req.params as { fileId: string };
try {
const file = await getFile(fileId, req.user.tenantId);
if (file === null)
return res.code(404).send({ error: "resource not found" });
const signedUrl = await getFileUrlS3(file.pid, file.name);
return res.code(200).send({ url: signedUrl });
} catch (err) {
return err;
}
}
export async function deleteFileHandler(
req: FastifyRequest,
res: FastifyReply
) {
const { fileId } = req.params as { fileId: string };
try {
const file = await getFile(fileId, req.user.tenantId);
if (file === null)
return res.code(404).send({ error: "resource not found" });
await deleteFileS3(file.pid);
await file.deleteOne();
return res.code(204).send();
} catch (err) {
return err;
}
}