Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: Blog API with Migrations

Build a blog API end to end: migrations, repositories, a transactional service, keyset pagination and an HTTP layer tested with fetch.

Time to combine what the previous lessons taught. In this project you will build the backbone of a blog: versioned migrations, repositories, a service that uses a transaction, keyset pagination and a small HTTP API you call with fetch. It runs entirely on Node's built-in modules.

Stand-in. The persistence layer here is hand-written on node:sqlite so it runs in the lesson. In a real project the repository classes would call TypeORM (repo.find, manager.save) or Sequelize (Post.findAll, Post.create) and the migration objects would be real TypeORM or Sequelize migrations. The architecture does not change, and each piece is mapped to the library call in a table at the end.

What you will build

flowchart LR
  C["HTTP client"] --> H["HTTP layer<br/>routes, JSON"]
  H --> S["PostService<br/>one transaction per use case"]
  S --> R1["UserRepo"]
  S --> R2["PostRepo"]
  S --> R3["TagRepo"]
  R1 --> D[("SQLite")]
  R2 --> D
  R3 --> D
  M["Migrations"] --> D

Requests flow down; only the service decides where a transaction starts and ends.

Step 1: migrations and the data layer

The schema comes from two ordered migrations, run by the same bookkeeping logic as in Why You Need Migrations. The second migration adds the tags tables to show an evolving schema. Repositories take the connection, and PostService.publish creates a post and its tags atomically.

Node.js Migrations, repositories and a transactional service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The ghost post fails the foreign key on author_id. Because the post insert comes first and the whole function sits in a transaction, nothing is half-written; no orphan tag appears. Tags are normalized (SQL and sql become one) and de-duplicated with a Set before inserting.

Step 2: the HTTP layer

Now put an HTTP server in front. It listens on a loopback port chosen by the system and calls itself with fetch. Routes: POST /users, POST /posts, GET /posts?after=<id>&limit=<n>. It returns 201, 404, 409 (duplicate email) and 422 (validation) so clients can tell failures apart.

Node.js The API, called with fetch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Map errors to status codes in one place (the catch block) and let the service throw HttpErrors that carry the meaning. Raw database messages never reach the client; they become a clean 409 or 404.

Mapping to TypeORM and Sequelize

Stand-in piece TypeORM Sequelize
migrations array classes implementing MigrationInterface files with up/down and queryInterface
users.create(d, ...) manager.getRepository(User).save(...) User.create(..., { transaction })
publish() with begin/commit dataSource.transaction(async (m) => ...) sequelize.transaction(async (t) => ...)
insert or ignore for tags repo.upsert(...) or orIgnore() in a query builder Tag.findOrCreate(...)
feed() with a join and limit find({ relations, where: { id: LessThan(after) }, order, take }) findAll({ include, where: { id: { [Op.lt]: after } }, order, limit })
Catch UNIQUE / FOREIGN KEY QueryFailedError with the driver code UniqueConstraintError, ForeignKeyConstraintError

Extensions to try

  1. Add PATCH /posts/:id with optimistic locking (a version column, see Locking and Isolation Levels).
  2. Count queries on GET /posts and assert it stays constant as the page size grows (N+1).
  3. Write a third migration that renames title to headline with the expand and contract steps.
  4. Cache the first feed page for ten seconds and invalidate it on every new post.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the publish function wrap both post and tag inserts in one transaction?

    A failure partway through would otherwise leave a post without its tags or tags without a post.
  2. 2. Which HTTP status fits a duplicate email on registration?

    409 Conflict tells the client the request clashes with existing state; 500 would hide a client-fixable problem.
  3. 3. Why should the service, not the HTTP layer, define the transaction boundary?

    The HTTP layer only translates requests; the use case decides what must succeed together.
  4. 4. What does the nextAfter value in the feed response represent?

    The client sends it back as after=<id> to continue exactly where the previous page ended.

Summary

  • Migrations create the schema; repositories hold queries; the service owns the transaction.
  • Normalize and de-duplicate input before writing, and let constraints be the final guard.
  • Translate database errors to meaningful HTTP statuses in one place.
  • Keyset pagination keeps the feed stable and fast.

Next: Project: Inventory Ledger