Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 42 ยท Projects

Project: Blog API with Relations

Build a blog API in NestJS: posts, comments and authors with relations, pagination with totals, and an interceptor that gives every response one shape.

A blog is a good second project because its data is related: an author writes many posts, a post has many comments, and every list needs pagination. These are the problems real APIs spend most of their time on: loading related rows without sending hundreds of queries, returning a page plus its total, hiding fields that must not leave the server, and giving every response the same envelope so clients can rely on it.

You will design the entities and endpoints, see the real Nest and TypeORM code (read-only, it needs npm and a database), and run a stand-in that uses Node's built-in SQLite (node:sqlite) with the same queries a repository would send. The stand-in is not Nest or an ORM. It shows the SQL behind relations, the N+1 problem and an interceptor that shapes responses.

The data model

Author Has many posts.
Post Belongs to an author, has many comments.
Comment Belongs to one post.

One-to-many twice, loaded on demand.

1 / 2

Entities and relations

With TypeORM (see Connecting to a Database and Repositories, Entities and Relations) the model looks like this:

TypeScript
@Entity()
export class Author {
  @PrimaryGeneratedColumn() id: number;
  @Column() name: string;

  @Exclude()                      // never serialized into responses
  @Column() email: string;

  @OneToMany(() => Post, (post) => post.author)
  posts: Post[];
}

@Entity()
export class Post {
  @PrimaryGeneratedColumn() id: number;
  @Column() title: string;
  @Column('text') body: string;
  @CreateDateColumn() createdAt: Date;

  @ManyToOne(() => Author, (author) => author.posts, { nullable: false })
  author: Author;

  @OneToMany(() => Comment, (comment) => comment.post)
  comments: Comment[];
}

@Entity()
export class Comment {
  @PrimaryGeneratedColumn() id: number;
  @Column() text: string;
  @ManyToOne(() => Post, (post) => post.comments, { onDelete: 'CASCADE' })
  post: Post;
}

Relations are not loaded unless you ask. The @Exclude() decorator is a class-transformer feature: when Nest's ClassSerializerInterceptor is active and your handlers return class instances, excluded properties are removed from the JSON.

Pagination with a total

A list endpoint must not return the whole table. The simplest scheme is page and limit, and clients also need the total to draw page links:

TypeScript
export class PageQuery {
  @Type(() => Number) @IsInt() @Min(1) page = 1;
  @Type(() => Number) @IsInt() @Min(1) @Max(50) limit = 10;
}

async findPage({ page, limit }: PageQuery) {
  const [items, total] = await this.posts.findAndCount({
    relations: { author: true },
    order: { createdAt: 'DESC', id: 'DESC' },   // stable order is essential
    skip: (page - 1) * limit,
    take: limit,
  });
  return new Paginated(items, total, page, limit);
}

Two traps. Without a stable ORDER BY (including a unique tie-breaker like id) rows can appear on two pages or none. And large OFFSET values get slow because the database still walks the skipped rows; for huge, scrolling lists, keyset pagination ("rows older than this id") scales better.

The N+1 problem

If you load ten posts and then ask for each post's author in a loop, you send 1 + 10 queries. With a hundred posts it is 101. The fix is to load relations in the same query (a JOIN) or in one extra batched query (WHERE id IN (...)). In TypeORM that is the relations option or a query builder with leftJoinAndSelect. Counting comments per post is the same story: use a grouped count, not a count per row.

An interceptor for the response shape

If every endpoint returns whatever it likes, clients need special cases. An interceptor can wrap results into one envelope:

TypeScript
@Injectable()
export class ResponseShapeInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    return next.handle().pipe(
      map((result) =>
        result instanceof Paginated
          ? { data: result.items, meta: { page: result.page, limit: result.limit, total: result.total } }
          : { data: result },
      ),
    );
  }
}

Registered globally with { provide: APP_INTERCEPTOR, useClass: ResponseShapeInterceptor }, controllers keep returning plain values, and the envelope is added in one place. Errors still go through exception filters, so keep their shape compatible (statusCode, message).

The stand-in: relations in SQL, and counting queries

The first demo builds the three tables in an in-memory SQLite database, seeds some rows and answers one question three ways: the N+1 way, the JOIN way, and the grouped-count way. A small wrapper counts queries so the difference is visible. SQLite via node:sqlite is still marked experimental in Node 24, so the runner may print a warning on standard error.

Node.js Relations, N+1 and a page with totals

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 first approach sends seven queries to render three posts, and it grows with the page size. The JOIN returns the same information in one. The grouped LEFT JOIN keeps posts without comments (count 0), which an inner join would silently drop. Deleting post 5 removed its three comments because of the foreign key's ON DELETE CASCADE, which in TypeORM is the onDelete: 'CASCADE' option shown above.

The stand-in: the API with an interceptor

The second demo is a small API over the same kind of database. Handlers return raw values or a Paginated object. A chain of interceptors then wraps the result: one strips fields marked as private (like @Exclude()), and one builds the { data, meta } envelope. The chain composition mimics how Nest wraps the handler, written with promises instead of RxJS.

Node.js Blog endpoints with shape and serializer interceptors

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.

Check three things in the output. Every success is wrapped in data, and list responses add meta with the total. The author's email never appears, neither inside the list nor inside the single post, because the serializer removed it everywhere. Errors keep their own small shape (statusCode, message) because the interceptors only run on success; in Nest, errors are the job of exception filters. The last page of the list holds one item, and the comment text was trimmed by the service before it was stored.

Design notes

  • Return DTOs, not entities, when shapes differ. Entities mirror tables. Responses are a public contract. Mapping to a response class lets you rename columns or hide internals without a migration.
  • Never trust limit. The cap (50 here) protects your database from a request for a million rows.
  • Choose what to load. The list loads the author and a count. The detail loads comments. Neither loads everything, because loading a whole graph "just in case" makes each endpoint slow.
  • Write paths need validation too. The comment endpoint validates length and trims; real code uses a DTO with decorators and the global validation pipe, plus an auth guard so only signed-in users comment (Project: Auth Service).
  • Transactions matter when one request changes several rows, for example creating a post and its tags together (Transactions and Migrations).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Rendering 3 posts with an author query and a comment-count query per post sends how many queries?

    One query for the posts plus two per post is 1 + 3 x 2 = 7. This is the N+1 pattern: the count grows with the page size. One JOIN with a grouped count does it in one query.
  2. 2. Why use a LEFT JOIN to count comments per post?

    An inner join drops posts that have no matching comment rows. A left join keeps them and COUNT of the comment id yields 0.
  3. 3. What does the response-shape interceptor do with a Paginated result?

    Paginated results are unpacked into data plus meta, while other results become { data: result }, so clients always read data.
  4. 4. Why include a unique column such as id in the ORDER BY of a paginated query?

    When many rows share the same created date, the database may order them differently from one query to the next. A unique tie-breaker makes the order deterministic.
  5. 5. What is the purpose of @Exclude() together with ClassSerializerInterceptor?

    class-transformer's @Exclude() marks properties to omit when instances are serialized. The data stays in the database and in memory, but never reaches the client.

Summary

  • Model one-to-many relations with @OneToMany and @ManyToOne; relations load only when you ask, and onDelete: 'CASCADE' keeps children consistent.
  • Paginate with page and limit, cap the limit, use a stable ORDER BY with a unique tie-breaker, and return the total; consider keyset pagination for very large lists.
  • Avoid N+1 by joining or batching, and use grouped counts with a LEFT JOIN.
  • An interceptor gives every successful response one envelope; a serializer (@Exclude() with ClassSerializerInterceptor) keeps private fields out.
  • Return response shapes, validate writes, and use transactions when a request changes several rows.

Continue with Project: Realtime Chat Gateway.