How-to › Run message-based services

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.

Audience
API producer
Level
beginner
Topic
Persist entities in services
Languages
TypeScript
Verified

Your handlers call pool.query with SQL strings in a dozen places, so every handler test starts PostgreSQL first and the suite takes minutes. When the customer table gains a column, you search for from customer, miss the query that uses an alias, and the handler that runs it returns the wrong shape to its caller.

What you get

You will end up with one CustomerRepository interface, implemented over node-postgres for the service and over a Map for handler tests, with a contract test that holds both to one behavior. This is for you if your handlers hold SQL.

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. 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 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, 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. The latest tag on npm points at a release candidate of Prisma ORM 8, which this page did not run.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
Drizzle in a data moduleYou want typed, SQL-shaped queries and the table declared in TypeScriptA schema file to keep in step with migrations, and errors wrapped in DrizzleQueryErrorYour queries are few and plain, so a query builder adds a dependency for little
Prisma client used directly in handlersA small service where each handler is one query and tests run against a databaseA handler test needs a database or a mocked client, and P2002 codes reach handler codeTwo handlers share a query, or tests must run with no database
repository modules over node-postgresYou write SQL and want every statement for a table in one fileRow mapping by hand, column names unchecked by the compiler, and SQL in stringsThe schema changes weekly, and typed queries would catch the drift at build time
TypeORM repositoriesThe codebase already uses TypeORM entities and its migrationsIts Repository returns entity instances, so a clean interface maps every resultHandlers 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. 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.

// 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.

// 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.

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.

node demo.ts
  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 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.

node --test repository.test.ts
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 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 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.

node pitfall.ts
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:

node errors.ts
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

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.

Footnotes

  1. The appendix of error codes 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. ↩︎ Back to text

  2. The entry for Repository in Martin Fowler’s catalog of patterns 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. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.