CodingNic

EPUB Upload & Storage

Clean Up Files When Books Are Deleted

EPUB Upload & Storage 18 min read

Clean Up Files When Books Are Deleted

Clean Up Files When Books Are Deleted

Task

Extend Book deletion so database records and stored objects do not drift apart.

Before deleting the Book, load the owned record:

ts
const book = await prisma.book.findFirst({
  where: {
    id: bookId,
    userId: user.id,
  },
});

if (!book) {
  return Response.json({ error: "Book not found" }, { status: 404 });
}

Delete the known storage keys:

ts
await Promise.all(
  [book.epubKey, book.coverKey]
    .filter(Boolean)
    .map((key) =>
      storage.send(
        new DeleteObjectCommand({
          Bucket: bucket,
          Key: key!,
        }),
      ),
    ),
);

Then delete the Book record.

If your data model has dependent records with cascading deletes, let Prisma/PostgreSQL handle those relationships.

For production robustness, consider making cleanup retryable if storage deletion fails.

Test

Upload a book, note its storage objects, delete the book through the custom dialog, and verify:

  • the Book is gone
  • its dependent data is gone as configured
  • its EPUB object is gone
  • its cover object is gone

Checkpoint

Deleting a Readly book cleans up both persistent application data and its stored files.

Module Complete

Readly now has real eBook files. Module 6 will use those files to initialize EPUB.js and turn the prepared Reader screen into an actual reader.