Patterns & principles · 8 of 10 · 15 min read
The Repository pattern
One boundary between your domain and wherever the data actually lives, so the rest of the app never learns the difference.
- Design patterns
A repository is the one place that knows where data comes from. Everything above it asks for things — a user, an order — and never for a row, a document or an HTTP response.
The leak it prevents
// A component that knows far too much:
async function OrderList() {
const res = await fetch('/api/v2/orders?status=paid&limit=20', {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
});
if (!res.ok) throw new Error('failed');
const json = await res.json();
return json.data.items.map((row) => ({ id: row.order_id, total: row.total_cents / 100 }));
}
The URL, the API version, the auth scheme, the envelope shape, the snake_case field names and the
fact that money arrives in cents are now facts about this component. Five components doing this
means five places to change when the API adds a version, and every test needs a fetch mock.
The repository
// orders-repository.js — the only module that knows what the API looks like
export function createOrderRepository({ http }) {
// storage shape in, domain shape out
const toOrder = (row) => ({
id: row.order_id,
total: row.total_cents / 100,
status: row.status,
placedAt: new Date(row.created_at),
});
return {
async findPaid({ limit = 20 } = {}) {
const { data } = await http.get(`/v2/orders?status=paid&limit=${limit}`);
return data.items.map(toOrder);
},
async findById(id) {
const { data } = await http.get(`/v2/orders/${id}`);
return data ? toOrder(data) : null; // not found is `null`, not a 404
},
async save(order) {
const { data } = await http.post('/v2/orders', {
order_id: order.id,
total_cents: Math.round(order.total * 100),
});
return toOrder(data);
},
};
}
// the component now reads as what it does
async function OrderList({ orders }) {
const paid = await orders.findPaid({ limit: 20 });
return paid.map((order) => `${order.id}: ${order.total}`);
}
Three things moved behind the boundary: the query (status=paid), the mapping (snake_case
and cents), and the error contract (missing is null, not an exception about HTTP).
Swapping the implementation
Because the caller only knows the method names, the storage can be anything:
// the same interface, backed by an array — for tests, for Storybook, for an offline mode
export function createInMemoryOrderRepository(seed = []) {
const rows = new Map(seed.map((order) => [order.id, order]));
return {
async findPaid({ limit = 20 } = {}) {
return [...rows.values()].filter((o) => o.status === 'paid').slice(0, limit);
},
async findById(id) {
return rows.get(id) ?? null;
},
async save(order) {
rows.set(order.id, order);
return order;
},
};
}
const orders = createInMemoryOrderRepository([
{ id: 1, total: 10, status: 'paid' },
{ id: 2, total: 20, status: 'draft' },
]);
console.log(await OrderList({ orders })); // ["1: 10"] — no fetch, no mock, no network
That is the pattern’s main return on investment: a test of the logic above it needs no mocking library, because the dependency is a parameter.
| Data access inline | Behind a repository | |
|---|---|---|
| Places that know the URL shape | every caller | one |
| Testing the caller | mock fetch |
pass an array-backed object |
| Changing API version | every caller | one file |
| Caching, retries, batching | copy-pasted | one place to add them |
| Offline or fixture mode | rewrite | a second implementation |
| Cost | none | a file and an indirection |
Keeping the contract honest
JavaScript has no interface, so nothing stops the two implementations drifting apart. The cheap
enforcement is one test run against both:
const implementations = {
http: () => createOrderRepository({ http: fakeHttp }),
memory: () => createInMemoryOrderRepository(seed),
};
for (const [name, make] of Object.entries(implementations)) {
const repo = make();
console.log(name, typeof repo.findById === 'function', (await repo.findById(999)) === null);
// every implementation must agree that "missing" is null
}
This “contract test” is worth more than the type would be: it checks behaviour — that both return
null rather than one throwing — and not just the shape.
Where the boundary goes
A repository speaks the domain’s language, not the storage’s. These are not repositories:
// A thin wrapper that renamed fetch and leaked everything anyway:
const bad = {
get: (url) => fetch(url).then((r) => r.json()),
};
// Storage vocabulary in the method names:
const alsoBad = {
selectWhere: (sql, params) => db.query(sql, params),
};
And this is:
const orders = {
findById: (id) => {},
findPaidSince: (date) => {},
save: (order) => {},
markShipped: (id) => {},
};
Related names, which interviewers do ask to distinguish:
| Term | Speaks | Scope |
|---|---|---|
| Repository | the domain — findPaidSince |
a collection of one kind of thing |
| DAO | the storage — selectOrdersByStatus |
one table or endpoint |
| Service | a use case — checkout(cart) |
orchestrates several repositories |
| Gateway / client | a protocol — get, post |
one external system |
The repository usually sits on top of a gateway: the http object injected above is the
gateway, and the repository turns its responses into domain objects.
Errors and cancellation
Two things that belong behind the boundary, because they are storage concerns:
export class NotFoundError extends Error {
constructor(what, id) {
super(`${what} ${id} was not found`);
this.name = 'NotFoundError';
}
}
export function createUserRepository({ http }) {
return {
async findById(id, { signal } = {}) {
try {
const { data } = await http.get(`/users/${id}`, { signal });
return data ? toUser(data) : null;
} catch (error) {
if (error.name === 'AbortError') throw error; // cancellation passes through
// everything else becomes a domain error, with the cause kept for the logs
throw new Error(`could not load user ${id}`, { cause: error });
}
},
};
}
The caller above never sees a status code, a JSON.parse failure or a TypeError: Failed to fetch. Passing a signal through is what lets a component cancel a request when it unmounts.
When not to bother
- A script, a prototype, or one call site. The indirection buys nothing until there are two callers or a test.
- When your data layer already is one. A generated API client, or a hook like
useQuerywith the query key and the mapping in one place, is already the boundary — wrapping it again just adds a file.
The honest answer in an interview is the trade-off: a repository costs one indirection and buys substitutability, and it is worth it exactly when something will be substituted — a test, a second backend, an offline mode.
Common mistakes
Returning the storage’s shape
Mistake. return data.items straight from the response.
Why it fails. Every caller now depends on order_id and total_cents, so the API’s naming is
the app’s naming and the boundary is decoration.
What to do instead. Map to the domain shape in the repository. That mapping function is the
boundary.
Letting the repository make decisions
Mistake. findPaid() that also sends an email or writes to a cache the caller did not ask for.
Why it fails. It is now a service with a repository’s name, and nobody can predict what reading
data does.
What to do instead. Keep it to retrieval and persistence; put the orchestration in a service
that uses it.
Importing it instead of injecting it
Mistake. import { orderRepository } from './orders-repository.js' inside a component.
Why it fails. The module is a singleton, so the dependency is invisible and a test cannot
substitute it without reaching into the module registry — which is the whole benefit, thrown away.
What to do instead. Pass it in, and let the application’s entry point decide which
implementation everyone gets.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
What does the Repository pattern do?
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.