Concepts
Repositories, filters and pages
How a module reads and saves its entities, filters rows with criteria, and returns lists one page at a time.
A repository is the class that reads a module’s entities from its table and saves them back. It exists so your use cases never write SQL: they ask it for entities with criteria, change them, and hand them back to save.
newt’s Repository already knows how to read, save, check versions and publish events. Your repository only says which table it uses and how a row becomes an entity.
A repository
Section titled “A repository”import { Repository } from '@newt-js/core'import type { ResolvedRow } from '@newt-js/core'import type { ContextBase } from '@newt-js/core/application'import type { z } from 'zod'// --------------------------------------------------------import { Task } from './task'import type { TaskSchema } from './task.schema'
export type TaskRow = z.infer<typeof TaskSchema> & { version: number }
export class Task_Repository extends Repository<Task, TaskRow> {
constructor(base: ContextBase) { super(base, base.database.records<TaskRow>('task'), { scope: 'none' }) }
protected toEntity(row: ResolvedRow<TaskRow, Task>): Task { return Task.fromDTO(row) }
}The constructor takes:
- The context’s base, for its transactions, its events and its use case runner.
base.database.records<TaskRow>('task'): the rows of the tabletask.- Options:
scope(required,'none'or a scope),softDelete(defaultfalse) and, when its entity references others,references. See Scope, Soft delete and References to other modules.
A repository has no public methods of its own. The lint rule repository-public-methods refuses them: what a module decides belongs in its use cases and its entity.
Reading
Section titled “Reading”| Method | Returns |
|---|---|
find(criteria?, options?) |
The matching entities. |
count(criteria?, options?) |
How many match. |
count(criteria, { by }) |
How many match, per value of the fields in by. |
paginate(criteria, page, options?) |
One page of matching entities. |
Options of find:
limit: at most this many.orderBy: a list of{ field, direction? },directionbeing'asc'(default) or'desc'. Without it, rows come by id, ascending. Ids are UUID v7, which grow with time, so that is oldest first.everyScope:truereads past the repository’s scope.
const [task] = await this.tasks.find({ id }, { limit: 1 })const open = await this.tasks.count({ doneAt: null })const perProject = await this.tasks.count({}, { by: ['projectId'] })// [{ projectId: '0190…', count: 4 }, …]Criteria
Section titled “Criteria”Criteria say which rows to read. They are a plain object, keyed by the row’s fields:
{ name: 'Write the docs' } // equal to{ name: { ieq: 'write the docs' } } // with an operator// several, all must hold{ createdAt: { gte: '2026-01-01', lt: '2026-02-01' } }{ doneAt: null } // the field is empty{ or: [{ name: 'A' }, { name: 'B' }] } // any of{ and: [{ projectId }, { doneAt: null }] } // all ofThe operators are those of filters:
| Operator | Matches when the value is |
|---|---|
eq |
equal to it |
ne |
not equal to it |
in |
one of a list |
gt / gte |
greater than / greater than or equal to it |
lt / lte |
less than / less than or equal to it |
ieq |
equal to it, ignoring the case of A to Z |
A field set to undefined is ignored, so optional criteria can be written inline. An empty {} matches every row.
Use cases rarely write criteria by hand: TaskFilter.toCriteria(filter) turns what a client sent into criteria.
Two helpers:
allOf(a, b)returns criteria matching both.matches(row, criteria)checks one object against criteria in memory.
A list that can grow is read one page at a time.
type PageRequest = { size: number, cursor?: string }type Page<T> = { items: T[], nextCursor?: string, total?: number }paginate(criteria, page, options?) returns up to page.size entities after page.cursor, and:
nextCursor: the id of the last item, only when there are more. Send it as the nextcursor.total: how many match the criteria in all.
Its options are newestFirst (true reads by id, descending) and everyScope.
Over HTTP, pageRequestFrom(request) reads ?size= and ?cursor= from the URL (see HTTP and routes).
Helpers for pages:
| Function | What it does |
|---|---|
mapPage(page, fn) |
A page with each item mapped. Items mapped to undefined are dropped. |
toPage(rows, { size, cursor, total? }) |
Builds a page from up to size + 1 rows: the extra row says there is a next page. |
allPages(read, size?) |
Calls read page after page, 100 at a time by default, and returns every item. |
const found = await this.tasks.paginate(criteria, page, { newestFirst: true,})return mapPage(found, each => each.toDTO())Saving
Section titled “Saving”await this.tasks.persist(task)await this.tasks.persist([task, another])persist(entities, hooks?) saves one entity or a list, all in one transaction:
- It checks the write rule.
- It writes each entity with something to save. A new one is inserted. A changed one updates only its changed fields,
updatedAtandversion. A deleted one is deleted. - It publishes the events each saved entity tracked, into the queue of jobs kept in the database (the outbox), in the same transaction. See Events and subscriptions.
Entities with nothing to save are skipped. If any write fails, the transaction rolls back and nothing is saved.
purge(criteria) deletes every matching row at once and returns how many. It builds no entities, checks no versions and publishes no events: keep it for clean-up jobs.
Save hooks and guards
Section titled “Save hooks and guards”persist takes optional hooks, which run inside its transaction:
| Hook | Runs |
|---|---|
before |
Before the writes. |
after |
After the writes, before the events. Needs guard. |
guard |
Names what the hooks protect, as a list of keys. |
A hook that reads must name a guard. Say a project holds at most 100 open tasks:
await this.tasks.persist(task, { guard: [`project:${projectId}`], before: async () => { if (await this.tasks.count({ projectId, doneAt: null }) >= 100) { throw new ProjectFull() } },})On Postgres and MySQL, the guard locks those keys until the transaction ends, so two saves for the same project take turns. A save waits up to 30 seconds for a key, then fails with GuardTimeout. On SQLite, writes already run one at a time.
Transactions
Section titled “Transactions”Each persist is one transaction. A module never opens one itself: the lint rule module-transactions refuses any use of the base’s transactions in a module. To save several entities together, pass them to one persist.
If a save fails inside a transaction that another save opened, the whole transaction rolls back, even if your code caught the error. newt then throws TransactionSpoiled, so a half-done save is never committed.
Versions and conflicts
Section titled “Versions and conflicts”Two people can change the same task at the same time. Without a check, the second save would silently overwrite the first. newt stops that with a number on every row, its version:
- An insert writes
version1. - An update or a delete runs only if the row’s version is still the one the entity read, and adds one to it.
- If the row changed in between, nothing is written and the save throws
StaleVersion.
This is what happens when two use cases complete the same task at once:
The errors a save can throw when it collides with another:
| Error | When | HTTP |
|---|---|---|
StaleVersion |
Someone saved the row since you read it, or deleted it. | 409 |
DuplicateValue |
A unique index refused a value. | 409 |
TransactionConflict |
Postgres or MySQL refused the transaction (a deadlock, a serialization failure). | 409 |
All three are ConcurrencyConflicts, so the use case runs again, up to three times by default, before the error reaches the client. DuplicateValue lists the fields in params.fields when the database says which.
References to other modules
Section titled “References to other modules”When its entity references entities of other modules (see Entities), a repository is given, in its options, how each one loads: the other module’s find, by id. Every read resolves them before it builds the entities:
export class Order_Repository extends Repository<Order, OrderRow> {
constructor(base: ContextBase, references: Loads<OrderReferences>) { super(base, base.database.records<OrderRow>('orders$order'), { scope: 'none', references }) }
protected toEntity(row: ResolvedRow<OrderRow, Order>): Order { return Order.fromDTO(row) // { customer, lines: [{ product, quantity }], version, ... } }
}The module gives it them in initialize, where it has its dependencies:
static initialize( base: ContextBase, router: HttpRouter, deps: Order_Deps,): Order_Module { const orders = new Order_Repository(base, { customerId: ids => deps.customers.customer.find({ field: 'id', op: 'in', value: ids }), lines: { productId: ids => deps.catalog.product.find({ field: 'id', op: 'in', value: ids }) }, }) const module = new Order_Module(base, orders, router, deps) // ...}- A read loads each reference once, for every row and every line in it: its distinct ids, 100 at a time, every reference at once. 50 orders of 20 customers with 200 lines of 30 products are two calls.
- It reads the other module only through its use case, never its table:
module-importsstill holds. - The row keeps the ids,
customerIdandlines[].productId: a save stores those, never the entities. - A repository whose entity has references does not compile without
references. - Every read pays for them, those of a write and of a worker too, and the other module resolves its own references in turn. A read too hot for that keeps its own copy of what it needs, fed by the other module’s events: a read model.
ReferenceNotFound (400, code reference_not_found) says an id points to nothing: The customer 0190… does not exist. A read throws it when an id it keeps names nothing any more: keep the ids alive by following the other module’s events. referenced throws it too when a use case takes from another module what its input names (see Use cases).
Text the database cannot keep
Section titled “Text the database cannot keep”A string holding the NUL character or a lone surrogate cannot be stored as text. Saving one throws TextWithNul (400, code text_with_nul). holdsNul(value) checks a value beforehand, inside strings, arrays and objects.
A scope keeps a repository to the rows of one owner, such as the current workspace:
super(base, base.database.records<TaskRow>('task'), { scope: { field: 'workspaceId', current: () => currentWorkspaceId() },})- Every read adds
workspaceId = current()to its criteria, unless it passeseveryScope: true. persistrefuses an entity of another scope, before writing.
See Actor and scope for where the current value comes from.
Soft delete
Section titled “Soft delete”With softDelete: true, a deleted entity keeps its row: the save sets deletedAt (and updatedAt) instead of deleting it, and every read skips rows with a deletedAt. The table needs a nullable deleted_at column.
Rows and entities
Section titled “Rows and entities”A repository turns rows into entities and back with three protected methods:
| Method | Default |
|---|---|
toEntity(row) |
None: you write it. The row comes with the entities its entity references in place of their ids. |
toRow(entity) |
The entity’s fields, for an insert. |
toChanges(entity) |
The changed fields and updatedAt, for an update. |
Override toRow and toChanges when the table and the entity differ. this.records gives the table itself: find, count, countBy, insert, update, delete and deleteMany.
With the CLI
Section titled “With the CLI”newt add module writes the repository with its module, its entity and its table:
newt add module tasks/taskSee newt add module.