import { ResultAsync, ok } from "neverthrow"; import { PrismaClientArg, Prisma, File } from "@repo/db"; import { fileNotFound, FileStorageError } from "../errors"; import { wrapDbOperation, wrapDbOperationWithNull, DatabaseError, databaseError, } from "@repo/exceptions"; import { CreateFileInput } from "../types"; const create = ( client: PrismaClientArg, data: CreateFileInput, ): ResultAsync => { const fileData: Prisma.FileCreateInput = { filename: data.filename, originalName: data.originalName, mimeType: data.mimeType, size: data.size, path: data.path, }; return wrapDbOperation( () => client.file.create({ data: fileData }), (e) => databaseError("createFile", e as Error), ); }; const findById = ( client: PrismaClientArg, id: string, ): ResultAsync => wrapDbOperationWithNull( () => client.file.findUnique({ where: { id } }), fileNotFound(id), (e) => databaseError("findFileById", e as Error), ); const findByFilename = ( client: PrismaClientArg, filename: string, ): ResultAsync => ResultAsync.fromPromise( client.file.findFirst({ where: { filename } }), (error) => databaseError("findByFilename", error as Error), ); const deleteById = ( client: PrismaClientArg, id: string, ): ResultAsync => ResultAsync.fromPromise(client.file.delete({ where: { id } }), (error) => databaseError("deleteFile", error as Error), ).andThen(() => ok(undefined)); const exists = ( client: PrismaClientArg, filename: string, ): ResultAsync => ResultAsync.fromPromise(client.file.exists({ filename }), (error) => databaseError("checkFileExists", error as Error), ); export const FileRepository = { create, findById, findByFilename, deleteById, exists, };