Add file handlers, s3 support
This commit is contained in:
73
src/file/file.controller.ts
Normal file
73
src/file/file.controller.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user