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;
}
}

50
src/file/file.route.ts Normal file
View File

@@ -0,0 +1,50 @@
import { FastifyInstance } from "fastify";
import {
deleteFileHandler,
fileDownloadHandler,
fileUploadHandler,
} from "./file.controller";
import { $file } from "./file.schema";
export async function fileRoutes(fastify: FastifyInstance) {
fastify.post(
"/upload",
{
schema: {
response: {
201: $file("uploadFileResponse"),
},
},
config: { requiredClaims: ["file:upload"] },
preHandler: [fastify.authorize],
},
fileUploadHandler
);
fastify.get(
"/:fileId",
{
schema: {
params: { type: "object", properties: { fileId: { type: "string" } } },
response: {
200: $file("downloadFileResponse"),
},
},
config: { requiredClaims: ["file:download"] },
preHandler: [fastify.authorize],
},
fileDownloadHandler
);
fastify.delete(
"/:fileId",
{
schema: {
params: { type: "object", properties: { fileId: { type: "string" } } },
},
config: { requiredClaims: ["file:delete"] },
preHandler: [fastify.authorize],
},
deleteFileHandler
);
}

40
src/file/file.schema.ts Normal file
View File

@@ -0,0 +1,40 @@
import { z } from "zod";
import mongoose from "mongoose";
import { buildJsonSchemas } from "fastify-zod";
export const fileModel = mongoose.model(
"file",
new mongoose.Schema({
tenantId: String,
pid: {
type: String,
unique: true,
required: true,
},
name: {
type: String,
required: true,
},
mimeType: String,
createdAt: Date,
createdBy: Date,
})
);
const uploadFileResponse = z.object({
pid: z.string(),
name: z.string(),
mimeType: z.string(),
});
const downloadFileResponse = z.object({
url: z.string().url(),
});
export const { schemas: fileSchemas, $ref: $file } = buildJsonSchemas(
{
uploadFileResponse,
downloadFileResponse,
},
{ $id: "file" }
);

22
src/file/file.service.ts Normal file
View File

@@ -0,0 +1,22 @@
import { fileModel } from "./file.schema";
export async function createFile(
pid: string,
name: string,
mimeType: string,
tenantId: string
) {
return await fileModel.create({
tenantId: tenantId,
pid: pid,
name: name,
mimeType: mimeType,
createdAt: new Date(),
});
}
export async function getFile(fileId: string, tenantId: string) {
return await fileModel.findOne({
$and: [{ tenantId: tenantId }, { pid: fileId }],
});
}