# How to add a repository layer between a service and its database

> Put one repository interface between service handlers and the database, so every query lives in one module and handler tests run against an in-memory fake.

Source: https://voxgig.com/howto/add-a-repository-layer-to-a-service

- Audience: api-producer
- Level: beginner
- Languages: typescript
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Define a `CustomerRepository` interface with the operations your handlers need, and implement it in one module over node-postgres that holds every SQL statement and copies each row into a plain `Customer`. Pass the repository to handlers as an argument, test the handlers against an in-memory fake, and run one contract test over both. Never return an ORM entity or a query builder through the interface.

---
## You will need

A service with at least one table, and Node 22.18 or later, which runs the sample's `.ts` files by
[stripping the types](https://nodejs.org/api/typescript.html). Verified 2026-11-30 against Node
22.23.5, pg 8.23.1, drizzle-orm 0.45.4, TypeORM 1.1.3 and `@prisma/client` 7.10.1.

The database in the sample is not a PostgreSQL server. It is [PGlite](https://pglite.dev/docs/)
0.6.1, a build of PostgreSQL compiled to WebAssembly that runs inside the Node process and reports
itself as `PostgreSQL 19.0 (PGlite 0.6.1)`. The sample serves it on a loopback port with
[`@electric-sql/pglite-socket`](https://pglite.dev/docs/pglite-socket), so all four clients connect
over the wire protocol. Every database behavior on this page was seen on that build.

The Prisma rows ran Prisma ORM 7, release 7.10.1, and link the
[Prisma ORM 7 documentation](https://www.prisma.io/docs/orm/v7/prisma-client/queries/crud). The
`latest` tag on npm points at a release candidate of Prisma ORM 8, which this page did not run.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Drizzle in a data module](https://orm.drizzle.team/docs/select) | You want typed, SQL-shaped queries and the table declared in TypeScript | A schema file to keep in step with migrations, and errors wrapped in `DrizzleQueryError` | Your queries are few and plain, so a query builder adds a dependency for little |
| [Prisma client used directly in handlers](https://www.prisma.io/docs/orm/v7/prisma-client/queries/crud) | A small service where each handler is one query and tests run against a database | A handler test needs a database or a mocked client, and `P2002` codes reach handler code | Two handlers share a query, or tests must run with no database |
| [repository modules over node-postgres](https://node-postgres.com/features/queries) | You write SQL and want every statement for a table in one file | Row mapping by hand, column names unchecked by the compiler, and SQL in strings | The schema changes weekly, and typed queries would catch the drift at build time |
| [TypeORM repositories](https://typeorm.io/docs/working-with-entity-manager/working-with-repository/) | The codebase already uses TypeORM entities and its migrations | Its `Repository` returns entity instances, so a clean interface maps every result | Handlers need plain data, or you want a fake that needs no ORM |

Drizzle and TypeORM fit behind the same interface, as the sample shows, and each then costs a
mapping step plus the ORM features the interface hides, such as TypeORM's
[lazy relations](https://typeorm.io/docs/relations/eager-and-lazy-relations/). Prisma
in handlers skips the layer and the mapping, and pays for it in tests: every handler test needs a
database or a mocked client. The node-postgres module costs the most typing and the fewest
dependencies.

## Define the interface handlers depend on

The interface names what handlers do with customers, in their words, and promises plain objects.

```ts title="customer.ts"
// The one interface handlers see. Plain data in, plain data out.
export type Customer = { id: number; email: string; name: string }
export type NewCustomer = { email: string; name: string }

export interface CustomerRepository {
  create(input: NewCustomer): Promise<Customer>
  findById(id: number): Promise<Customer | undefined>
  findByEmail(email: string): Promise<Customer | undefined>
  rename(id: number, name: string): Promise<Customer | undefined>
}
```

A duplicate email is part of the contract too. Each implementation throws `DuplicateEmailError`,
so no handler sees a driver's error type.

## Keep every statement in one module

The node-postgres implementation holds the four statements and copies each row through `toCustomer`,
which keeps the three promised fields and drops anything else the row carries.

```ts title="pg-repository.ts"
// Every SQL statement the service runs against the customer table lives here.
export function pgCustomerRepository(pool: pg.Pool): CustomerRepository {
  async function one(text: string, values: unknown[]): Promise<Customer | undefined> {
    const { rows } = await pool.query(text, values)
    return rows[0] ? toCustomer(rows[0]) : undefined
  }

  return {
    async create({ email, name }) {
      try {
        const created = await one(
          'insert into customer (email, name) values ($1, $2) returning id, email, name',
          [email, name],
        )
        return created!
      } catch (err) {
        if (isUniqueViolation(err)) throw new DuplicateEmailError(email)
        throw err
      }
    },
    findById: (id) => one('select id, email, name from customer where id = $1', [id]),
    findByEmail: (email) => one('select id, email, name from customer where email = $1', [email]),
    rename: (id, name) =>
      one('update customer set name = $2 where id = $1 returning id, email, name', [id, name]),
  }
}
```

Handlers take the repository as an argument. Nothing in `handlers.ts` imports `pg`.

```ts title="handlers.ts"
export async function registerCustomer(repo: CustomerRepository, input: { email?: string; name?: string }): Promise<Reply> {
  const email = input.email?.trim().toLowerCase()
  const name = input.name?.trim()
  if (!email || !email.includes('@') || !name) return { status: 400, body: { error: 'email and name are required' } }
  try {
    return { status: 201, body: await repo.create({ email, name }) }
  } catch (err) {
    if (err instanceof DuplicateEmailError) return { status: 409, body: { error: 'email already registered' } }
    throw err
  }
}
```

## Run one set of handlers over four stores

The demo registers a customer, registers the same email again, renames the first customer, and asks
for a second one, through each implementation. The last line runs a handler that calls Prisma
Client with no repository between them.

```bash
node demo.ts
```

```text output
  201 {"id":1,"email":"ada@example.com","name":"Ada"}
  409 {"error":"email already registered"}
  200 {"id":1,"email":"ada@example.com","name":"Ada Lovelace"}
  404 {"error":"not found"}
node-postgres   same replies
Drizzle         same replies
TypeORM         same replies
in-memory fake  same replies
Prisma in handlers, no repository: 201 {"id":1,"email":"ada@example.com","name":"Ada"} | 409 {"error":"email already registered"} | 404 {"error":"not found"}
```

The Prisma handler gives the same replies, and it has to know `P2002`, Prisma's
[code](https://www.prisma.io/docs/orm/v7/reference/error-reference) for a failed unique
constraint, to send the 409.

## Check it worked

The suite runs two contract tests over each implementation, the handler tests over the fake with no
database, the leak below, and the Prisma handler.

```bash
node --test repository.test.ts
```

```text output
1..12
# tests 12
# suites 0
# pass 12
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

The contract test asserts that every result is a plain object with exactly `id`, `email` and
`name`, using `node:assert/strict`, whose
[`deepStrictEqual`](https://nodejs.org/api/assert.html) compares prototypes. Drop `toCustomer` from
the TypeORM `create` and the TypeORM contract test fails.

A fake that drifts from the database fails the same tests. The second one holds every store to what
PostgreSQL refuses: a duplicate email, an id outside the `integer` type, and a NUL character in text.
It also checks that a failed insert spends an id, because a
[sequence value](https://www.postgresql.org/docs/19/functions-sequence.html) is not reclaimed when
its transaction aborts.

## When it goes wrong

The interface returns whatever the store returns. A layer that hands out TypeORM's own `Repository`
gives callers TypeORM calls and entity instances, so the store leaks into every handler.

```bash
node pitfall.ts
```

```text output
leaky: the layer hands out TypeORM
  over TypeORM                     returns CustomerEntity, deepStrictEqual to the plain record: false
  over the in-memory fake          throws TypeError: customers.findOneBy is not a function
fixed: the layer returns Customer
  over TypeORM                     returns Object, deepStrictEqual to the plain record: true
  over the in-memory fake          returns Object, deepStrictEqual to the plain record: true
```

The leaky handler cannot run against the fake, and its result fails a strict comparison with the
record a test expects. Map every result through `toCustomer` inside the repository, and never
return a query builder for the caller to finish.

A duplicate email surfaces as a different error in each store. PostgreSQL reports a unique
violation as SQLSTATE `23505`,[^1] and the clients wrap it in four ways:

```bash
node errors.ts
```

```text output
node-postgres  DatabaseError                  code=23505  cause.code=-      isUniqueViolation=true
Drizzle        DrizzleQueryError              code=-      cause.code=23505  isUniqueViolation=true
TypeORM        QueryFailedError               code=23505  cause.code=-      isUniqueViolation=true
Prisma Client  PrismaClientKnownRequestError  code=P2002  cause.code=-      isUniqueViolation=false
```

`isUniqueViolation` walks the cause chain, so it finds the code under Drizzle's wrapper. Translate
the error inside the repository, where the store's types are in scope, and throw your own.

## When not to do this

Do not add the layer to a service with three queries and one handler each. The interface, the fake
and the contract test cost more lines than the queries. PGlite runs the real schema in the test
process, so a handler can be tested against it directly.

In a service with about ten queries, count the queries that two handlers share. If none do, and
the tests run against a database anyway, the interface buys a swap of store that may never happen, at the
cost of a hop on every call.

Do not wrap an ORM and then keep using its features through the wrapper. A repository over TypeORM
that returns entities, or over Drizzle that returns a query, adds a hop but isolates nothing,
because every caller still depends on the types the ORM defines.

Skip the layer when each handler runs one query and its tests run against a database anyway. Prisma
Client in the handler is shorter, and its generated types already check every field. Choose
the layer once two handlers share a query, or once handler tests need to run without a database.[^2]

## Related how-tos

- [Choose an id scheme for service entities](/howto/choose-entity-ids-for-a-service-database)

- [Emit TypeScript types and SQL from one application model](/howto/generate-typescript-types-and-sql-from-one-model)

- [Split a monolith into message-based services with Seneca](/howto/split-a-monolith-into-message-based-services)

- [Evaluate message rules with json-rules-engine](/howto/evaluate-message-rules-with-json-rules-engine)

- [Separate service logic from its transport](/howto/separate-service-logic-from-the-transport)

## Last verified

Verified 2026-11-30 against Node 22.23.5, pg 8.23.1, `@electric-sql/pglite` 0.6.1,
`@electric-sql/pglite-socket` 0.3.1, drizzle-orm 0.45.4, TypeORM 1.1.3, and `@prisma/client` and
`@prisma/adapter-pg` 7.10.1, with the client generated by Prisma CLI 7.10.1. Every output block is
what the preceding command printed.

[^1]: The
[appendix of error codes](https://www.postgresql.org/docs/19/errcodes-appendix.html) says every
server message gets a five-character code that follows the SQL standard's conventions for SQLSTATE,
with the first two characters naming a class. Class 23 is Integrity Constraint Violation, and
`23505` is `unique_violation` within it. The appendix advises testing the code rather than the
message text, because the codes change less often across releases and are not translated.

[^2]: The entry for Repository in Martin Fowler's
[catalog of patterns](https://martinfowler.com/eaaCatalog/repository.html) is credited to Edward
Hieatt and Rob Mee. It describes the pattern as acting like an in-memory domain object collection. The fake in this sample takes the description literally.