04 / 12

What is the difference between a service and a repository in NestJS?

A service contains business logic and orchestrates calls to repositories, other services, or external APIs. A repository is a data-access abstraction that handles persistence concerns such as queries and transactions. Services are injected with repositories — this keeps business logic and data access cleanly separated.

Service using an injected repository
Separation of concerns:
  1. 1

    Service — owns business rules, validation logic, and orchestration.

  2. 2

    Repository — owns data access: queries, inserts, updates, transactions.

  3. 3

    This separation makes services easier to unit test (mock the repository).

  4. 4

    TypeORM provides Repository<Entity> via @InjectRepository() out of the box.