CodingNic

Persist Reading Progress

Create the Progress API

Persist Reading Progress 15 min read

Create the Progress API

Create the Progress API

Task

Create an authenticated API for reading progress.

Route

Create:

text
app/api/books/[bookId]/progress/route.ts

Load the current user and verify that the Book belongs to that user before reading or writing progress.

For a read:

ts
const progress = await prisma.readingProgress.findUnique({
  where: {
    bookId_userId: {
      bookId,
      userId: user.id,
    },
  },
});

For a write, use an upsert:

ts
await prisma.readingProgress.upsert({
  where: {
    bookId_userId: {
      bookId,
      userId: user.id,
    },
  },
  create: {
    bookId,
    userId: user.id,
    cfi,
    percentage,
  },
  update: {
    cfi,
    percentage,
  },
});

Adapt the field names to the existing Prisma schema.

Test

Open the endpoint while authenticated and unauthenticated. Try a Book owned by another user.

Checkpoint

Readly has a user-scoped progress API that can read and write one progress record per Book.