Patterns & principles · 7 of 10 · 16 min read
The Repository pattern
A collection-shaped interface over storage — and in TypeScript a generic contract the compiler checks, with the entity's id type as a parameter rather than an assumption.
- Design patterns
A repository makes storage look like a collection: find, save, delete. The application talks
to the interface and never to the database, so the storage can be swapped — including for an array
in a test.
The contract
interface Entity<Id> {
readonly id: Id;
}
interface Repository<T extends Entity<Id>, Id = string> {
find(id: Id): Promise<T | null>;
findAll(): Promise<readonly T[]>;
save(entity: T): Promise<T>;
create(data: Omit<T, "id">): Promise<T>;
delete(id: Id): Promise<boolean>;
}
Five methods and a shape, and everything interesting is in the types:
Idis a parameter, defaulted tostring. ARepository<Order, number>is a different type from aRepository<User>, and passing one where the other is expected is an error.findreturnsT | null, so every caller has to handle the miss. That is the single most valuable line in the interface.createtakesOmit<T, "id">, because the id is the storage’s job. The caller cannot supply one, and cannot forget the other fields.findAllreturnsreadonly T[], so a caller cannot push into what the repository handed back.
The source material for this track builds a Repository<T> and implements it by fixing the
parameter to one entity. That is the right instinct, and the version above adds what it was
missing: a separate id type, and a create shape that is not the full entity.
Two implementations of one interface
interface User { readonly id: string; name: string; email: string }
interface Repository<T extends { id: Id }, Id = string> {
find(id: Id): Promise<T | null>;
findAll(): Promise<readonly T[]>;
create(data: Omit<T, "id">): Promise<T>;
delete(id: Id): Promise<boolean>;
}
class InMemoryUserRepository implements Repository<User> {
#users = new Map<string, User>();
async find(id: string) { return this.#users.get(id) ?? null; }
async findAll() { return [...this.#users.values()]; }
async create(data: Omit<User, "id">) {
const user: User = { id: crypto.randomUUID(), ...data };
this.#users.set(user.id, user);
return user;
}
async delete(id: string) { return this.#users.delete(id); }
}
const repo = new InMemoryUserRepository();
const created = await repo.create({ name: "Ana", email: "a@b.c" });
console.log((await repo.find(created.id))?.name);
implements Repository<User> is the audit: remove a method or get a signature wrong and the error
appears on the class, not at the first call site. The second implementation is the same exercise
against real storage:
interface User { readonly id: string; name: string; email: string }
interface Row { user_id: string; full_name: string; email_address: string }
interface Db { query<T>(sql: string, params?: readonly unknown[]): Promise<T[]> }
class SqlUserRepository {
constructor(private readonly db: Db) {}
#toUser(row: Row): User {
return { id: row.user_id, name: row.full_name, email: row.email_address };
}
async find(id: string): Promise<User | null> {
const rows = await this.db.query<Row>("select * from users where user_id = $1", [id]);
return rows[0] ? this.#toUser(rows[0]) : null;
}
async findAll(): Promise<readonly User[]> {
return (await this.db.query<Row>("select * from users")).map((row) => this.#toUser(row));
}
}
declare const db: Db;
console.log(typeof new SqlUserRepository(db).find);
The #toUser mapper is the point of the boundary. The database’s column names stay in this file;
the application sees User. When a column is renamed, exactly one function changes — and the
compiler finds it, because Row and User are separate declarations on purpose.
Dependency inversion, concretely
interface User { readonly id: string; name: string; email: string }
interface UserRepository {
find(id: string): Promise<User | null>;
create(data: Omit<User, "id">): Promise<User>;
}
class RegisterUser {
constructor(private readonly users: UserRepository) {}
async execute(name: string, email: string): Promise<User> {
const existing = await this.users.find(email);
if (existing) throw new Error("already registered");
return this.users.create({ name, email });
}
}
// Production:
declare const sqlUsers: UserRepository;
const register = new RegisterUser(sqlUsers);
// A test, with no database, no mocking library and no stubs:
const stored: User[] = [];
const fake: UserRepository = {
async find(id) { return stored.find((user) => user.id === id) ?? null; },
async create(data) {
const user = { id: "test-1", ...data };
stored.push(user);
return user;
},
};
console.log((await new RegisterUser(fake).execute("Ana", "a@b.c")).id); // "test-1"
console.log(typeof register.execute);
RegisterUser depends on an interface it could have declared itself, and the database depends on
the same interface from the other side. Neither knows about the other — that is the inversion, and
the fake above is what it buys.
Queries that do not fit
The honest weakness of the pattern: real applications need more than find and findAll, and
every addition is a method on the interface that every implementation must provide.
| Approach | Good | Bad |
|---|---|---|
A method per query (findByEmail) |
explicit, easy to optimise | the interface grows without limit |
| A typed filter object | one method covers many queries | the filter type becomes a query language |
| A specification object | composable, testable | more machinery than most apps need |
| Expose the query builder | full power | the abstraction is gone |
The typed filter, which is the usual middle ground:
interface User { readonly id: string; name: string; email: string; active: boolean }
type Filter<T> = {
[K in keyof T]?: T[K] | { in: readonly T[K][] };
};
interface Queryable<T> {
findMany(filter: Filter<T>, options?: { limit?: number }): Promise<readonly T[]>;
}
declare const users: Queryable<User>;
console.log(typeof users.findMany);
// users.findMany({ active: true, name: { in: ["Ana", "Beto"] } });
// users.findMany({ activ: true }); // caught — not a key of User
Filter<T> is a mapped type over the entity, so the filter cannot name a field that does not
exist and cannot compare it to the wrong type. The warning sign is when the filter starts growing
or, not and orderBy: at that point you have written a query language, and using the ORM’s is
better than maintaining your own.
Splitting reads from writes
A smaller, very effective refinement — and one that interacts with variance:
interface User { readonly id: string; name: string }
interface ReadRepository<T, Id = string> {
find(id: Id): Promise<T | null>;
findAll(): Promise<readonly T[]>;
}
interface WriteRepository<T extends { id: Id }, Id = string> {
save(entity: T): Promise<T>;
delete(id: Id): Promise<boolean>;
}
// A read-only consumer asks for exactly what it needs.
async function renderList(users: ReadRepository<User>) {
return (await users.findAll()).map((user) => user.name);
}
declare const repo: ReadRepository<User> & WriteRepository<User>;
console.log(typeof renderList, typeof repo.save);
A function that takes ReadRepository<User> cannot write, and its fake is two methods instead of
six. This is Interface Segregation applied to the pattern, and it is the change that most often
makes a repository pleasant rather than ceremonial.
When not to bother
- A thin application over one database. A modern ORM is already the abstraction; wrapping it in a repository that forwards every call adds a layer and removes capability.
- A repository per table, mechanically. Repositories belong to aggregates — the unit the
application reasons about — not to tables. One
OrderRepositorythat loads the order with its lines is more useful than three table repositories the caller has to join. - An interface with one implementation and no tests. The seam is only worth its cost if something uses it.
Common mistakes
find returning T instead of T | null
Mistake. find(id: string): Promise<User>.
Why it fails. The miss is real and now invisible: callers use the result directly and get
undefined at runtime, which the type system promised could not happen.
What to do instead. T | null, and a separate findOrFail that throws when absence is
genuinely exceptional.
Leaking the storage type through the interface
Mistake. find(id: string): Promise<UserRow | null>, or a method taking a SQL fragment.
Why it fails. Every consumer now depends on the database schema, which is exactly what the
pattern exists to prevent. Swapping the implementation means changing the application.
What to do instead. A domain type and a mapper inside the implementation. The row type never
leaves the file.
create(entity: T) with the id included
Mistake. Taking the whole entity on create.
Why it fails. The caller has to invent an id the storage is going to replace, and nothing
stops them passing one that collides.
What to do instead. Omit<T, "id"> — or Omit<T, "id" | "createdAt"> for the fields storage
owns.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
What does TypeScript add to the Repository pattern?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.