|
| 1 | +import { RuntimeError, ScriptContext } from "../_gen/scripts/prepare.ts"; |
| 2 | +import { getKey } from "../utils/types.ts"; |
| 3 | +import { deleteKeys } from "../utils/bucket.ts"; |
| 4 | + |
| 5 | +export interface Request { |
| 6 | + uploadId: string; |
| 7 | +} |
| 8 | + |
| 9 | +export interface Response { |
| 10 | + bytesDeleted: string; |
| 11 | +} |
| 12 | + |
| 13 | +export async function run( |
| 14 | + ctx: ScriptContext, |
| 15 | + req: Request, |
| 16 | +): Promise<Response> { |
| 17 | + const bytesDeleted = await ctx.db.$transaction(async (db) => { |
| 18 | + const upload = await db.upload.findFirst({ |
| 19 | + where: { |
| 20 | + id: req.uploadId, |
| 21 | + completedAt: { not: null }, |
| 22 | + deletedAt: null, |
| 23 | + }, |
| 24 | + select: { |
| 25 | + id: true, |
| 26 | + userId: true, |
| 27 | + bucket: true, |
| 28 | + contentLength: true, |
| 29 | + files: true, |
| 30 | + createdAt: true, |
| 31 | + updatedAt: true, |
| 32 | + completedAt: true, |
| 33 | + }, |
| 34 | + }); |
| 35 | + if (!upload) { |
| 36 | + throw new RuntimeError( |
| 37 | + "upload_not_found", |
| 38 | + { |
| 39 | + cause: `Upload with ID ${req.uploadId} not found`, |
| 40 | + meta: { modified: false }, |
| 41 | + }, |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + const filesToDelete = upload.files.map((file) => |
| 46 | + getKey(file.uploadId, file.path) |
| 47 | + ); |
| 48 | + const deleteResults = await deleteKeys(ctx.userConfig.s3, filesToDelete); |
| 49 | + |
| 50 | + const failures = upload.files |
| 51 | + .map((file, i) => [file, deleteResults[i]] as const) |
| 52 | + .filter(([, successfullyDeleted]) => !successfullyDeleted) |
| 53 | + .map(([file]) => file); |
| 54 | + |
| 55 | + if (failures.length) { |
| 56 | + const failedPaths = JSON.stringify(failures.map((file) => file.path)); |
| 57 | + throw new RuntimeError( |
| 58 | + "failed_to_delete", |
| 59 | + { |
| 60 | + cause: `Failed to delete files with paths ${failedPaths}`, |
| 61 | + meta: { modified: failures.length !== filesToDelete.length }, |
| 62 | + }, |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + await db.upload.update({ |
| 67 | + where: { |
| 68 | + id: req.uploadId, |
| 69 | + }, |
| 70 | + data: { |
| 71 | + deletedAt: new Date().toISOString(), |
| 72 | + }, |
| 73 | + }); |
| 74 | + |
| 75 | + return upload.contentLength.toString(); |
| 76 | + }); |
| 77 | + return { bytesDeleted }; |
| 78 | +} |
0 commit comments