Repositories
Repositories provide type-safe CRUD operations. Use @repository decorator with both model and dataSource for auto-discovery. A repository over another service's API has no model - declare it type: RepositoryTypes.REMOTE (Read another service's API).
Pattern 1: Zero Boilerplate (Recommended)
The simplest approach - everything is auto-resolved:
// src/repositories/configuration.repository.ts
import { Configuration } from '@/models/entities';
import { PostgresDataSource } from '@/datasources/postgres.datasource';
import { DefaultCRUDRepository, repository } from '@venizia/ignis';
@repository({
model: Configuration,
dataSource: PostgresDataSource,
})
export class ConfigurationRepository extends DefaultCRUDRepository<typeof Configuration.schema> {
// No constructor needed!
async findByCode(opts: { code: string }) {
return this.findOne({ filter: { where: { code: opts.code } } });
}
async findByGroup(opts: { group: string }) {
return this.find({ filter: { where: { group: opts.group } } });
}
}Pattern 2: Explicit @inject
When you need constructor control (e.g., read-only repository or additional dependencies):
// src/repositories/user.repository.ts
import { User } from '@/models/entities';
import { PostgresDataSource } from '@/datasources/postgres.datasource';
import { inject, ReadableRepository, repository } from '@venizia/ignis';
import { CacheService } from '@/services/cache.service';
@repository({ model: User, dataSource: PostgresDataSource })
export class UserRepository extends ReadableRepository<typeof User.schema> {
constructor(
// First parameter MUST be DataSource injection
@inject({ key: 'datasources.PostgresDataSource' })
dataSource: PostgresDataSource, // Must be concrete type, not 'any'
// After first arg, you can inject any additional dependencies
@inject({ key: 'services.CacheService' })
private cacheService: CacheService,
) {
super(dataSource);
}
async findByRealm(opts: { realm: string }) {
// Use injected dependencies
const cached = await this.cacheService.get(`user:realm:${opts.realm}`);
if (cached) {
return cached;
}
return this.findOne({ filter: { where: { realm: opts.realm } } });
}
}Important:
- First constructor parameter MUST be the DataSource injection
- After the first argument, you can inject any additional dependencies you need
- When
@injectis at param index 0, auto-injection is skipped
Repository Hierarchy
AbstractRepository (engine-neutral base in src/base - lazy dataSource/entity resolution,
@model settings getters: properties.hidden, query.filter, query.limit.default)
↓
PostgresBaseRepository (postgres connector - filter building, hidden-column exclusion,
default-filter merging, transaction-aware connector resolution)
↓
ReadableRepository (read-only: find, findOne, findById, findEvery, count, existsWith)
↓
PersistableRepository (+ create, createAll, updateById, updateEach, updateBy, deleteById, deleteBy)
↓
DefaultCRUDRepository (no additional methods - recommended default)
↓
SoftDeletableRepository (overrides delete to set deletedAt timestamp)| Type | Description |
|---|---|
ReadableRepository | Read-only operations. Write operations throw errors. |
PersistableRepository | Read + write operations (create, update, delete). Extends ReadableRepository. |
DefaultCRUDRepository | Extends PersistableRepository with no additional logic. Recommended for most use cases. |
SoftDeletableRepository | Extends DefaultCRUDRepository. Overrides delete to set deletedAt timestamp instead of physically removing records. |
Querying Data
For advanced filtering with operators like gt, lt, like, in, between, and more, see Filter System.
Return shapes: read methods return values directly (find returns an array, findOne/findById return a record or null, count returns { count }), while write methods (create, updateById, deleteById, ...) return a { count, data } envelope.
const repo = this.get<ConfigurationRepository>({ key: 'repositories.ConfigurationRepository' });
// Find multiple records
const configs = await repo.find({
filter: {
where: { group: 'SYSTEM' },
limit: 10,
order: ['createdAt DESC'],
}
});
// Find one record
const config = await repo.findOne({
filter: { where: { code: 'APP_NAME' } }
});
// Select specific fields (array format)
const configCodes = await repo.find({
filter: {
fields: ['id', 'code', 'group'], // Only these fields returned
limit: 100,
}
});
// Order by JSON/JSONB nested fields
const sorted = await repo.find({
filter: {
order: ['metadata.priority DESC', 'createdAt ASC'],
}
});
// Create a record - write operations return a { count, data } envelope
const { data: newConfig } = await repo.create({
data: {
code: 'NEW_SETTING',
group: 'SYSTEM',
description: 'A new setting',
}
});
// Update by ID - also returns { count, data }
const { data: updatedConfig } = await repo.updateById({
id: 'uuid-here',
data: { description: 'Updated description' }
});
// Delete by ID - also returns { count, data }
await repo.deleteById({ id: 'uuid-here' });Different data for each row with updateEach
updateBy writes one data to every row it matches. updateEach gives each row its own:
const { count, data } = await repo.updateEach({
rows: [
{ id: 'uuid-1', data: { description: 'First' } },
{ id: 'uuid-2', data: { description: 'Second' } },
],
});It runs one update per row, in the order given, inside one transaction: a refused payload or a failed statement writes nothing. Pass options: { transaction } to join yours, and the repository leaves the commit to you. Each row goes through the same rules as updateById - the default filter, the row scope, hidden fields and the audit stamps - so data[i] is null and the row adds 0 to count when it does not match (missing, outside the scope, soft deleted). A repeated id runs once per occurrence and adds to count each time. updateEach is N statements, not one; shouldReturn: false returns data: null, and empty rows return { count: 0, data: [] } without opening a transaction. Relational repositories only.
Upsert
upsert inserts a row, or updates the row that already holds its key. It is one statement, INSERT ... ON CONFLICT (key) DO UPDATE, with no read before it, on Postgres, PGlite and SQLite. Relational repositories only.
The key is a handle declared once with UniqueKeys.of (see Unique Keys). Without on, the key is the primary key.
const cache = this.get<SelfOrderCacheRepository>({ key: 'repositories.SelfOrderCacheRepository' });
// `merchantId` is not named: `write.mode: 'assign'` fills it from the scope.
const { data } = await cache.upsert({
data: { cacheKey, value, expiresAt },
on: SelfOrderCache.keys.merchantCacheKey,
});
// Only `value` is refreshed when the row exists; `expiresAt` is written on insert only.
await cache.upsert({
data: { cacheKey, value, expiresAt },
on: SelfOrderCache.keys.merchantCacheKey,
update: ['value'],
});
// By primary key.
await settingRepo.upsert({ data: { id: 'theme', value: 'dark' } });It returns { count, data } like create: the written row, without hidden fields. options takes what create takes (transaction, shouldReturn, log).
update lists the columns the update branch writes. Without it, every column data sets, except the key's columns, the primary key and createdAt/createdBy. The compiler refuses an unknown column and createdAt/createdBy. A column of the key, a primary key column, or one data does not set, is refused when the call runs, before any SQL. A hand-built key that names a column the table does not have is refused the same way.
The rules are the rules of create and update:
- Both branches are guarded. The new row passes the write guard as a create, before any SQL. Under
write.mode: 'assign', a missing scope column is filled from the scope. The columns the update branch writes pass it as an update. - The existing row must be yours. The update branch only touches a row inside your scope and the model's default filter. If the row holding the key is outside them (another merchant's, or soft deleted), it is left as it is and the call fails with the same 403 write-denied error an out-of-scope write gets.
shouldSkipDefaultFilteris ignored. - Every key column needs a value. A null never conflicts in SQLite or in default Postgres, so the upsert would insert a duplicate each time. A null or missing key column is refused with a 400, unless the key is a
nullsNotDistinct()unique constraint (Postgres 15+). A scope column thatassignfills counts as set. - A partial index sends its
wherewith the conflict target, so a soft-deleted twin is not a conflict: a new row is inserted next to it. A row you send with the soft-delete column already set does not satisfy a partial key's predicate either, so it never conflicts: it is inserted as a new, already-deleted row. - Defaults apply on insert.
$onUpdatecolumns (modifiedAt,modifiedBy) apply on the update branch, as inupdate.createdAtandcreatedBynever change. - Hidden fields are written like
createwrites them, and never returned. - A
throughmodel checks its parents and writes in one transaction, ascreatedoes. - As the first call on a datasource that opens on first use, it opens it.
Two upserts of one key at the same time leave one row: the database resolves the conflict inside the statement. There is no upsertAll yet.
Reading every row, a page at a time
A batch job or an export has to read every row a filter matches without loading them all at once. findEvery is an async iterator that yields one page (an array of rows) per iteration:
for await (const page of repo.findEvery({
filter: { where: { status: 'ACTIVE' }, fields: ['id', 'email'] },
pageSize: 200,
})) {
await exportRows(page);
}Each page reads the rows whose id is above the last id of the page before, in ascending id order. A row inserted or deleted while the loop runs never shifts the window and no offset grows: a new row with a smaller id than the last one read is not visited, one with a larger id is, and no row comes twice.
- Pages. Every page holds
pageSizerows except the last, which may be shorter. An empty result yields no page. When the last page is full, one more query runs, finds nothing and yields nothing. - Same rules as
find. Every page is afind, so the default filter, the row scope (access) and the hidden fields apply to each one.optionsis passed to every page:transaction(every page reads through it),shouldSkipDefaultFilter,lock. - The key owns the order and the window. A filter with
order,limit,skip,offsetorincludeis refused with a 400.whereandfieldswork.idis read for the cursor even whenfieldsleaves it out, and is not in the rows then. The type of a page followsfields, as withfind. pageSizeis an integer: 500 when omitted, at least 1, at most 10 000 and at most the model'slimit.max(1000 unless the model sets it). A value outside that is a 400, and a model whoselimit.maxis below 500 lowers the default to it.- Stopping.
break,returnor a throw in the loop ends it, and no further query is made. - One key. The model's
idmust be a single-column primary key and must not be a hidden property; anything else is a 400. - Where it throws. Every refusal surfaces on the first iteration, not when
findEveryis called. - Relational repositories only.
Extra Options
All repository operations accept an options parameter with these fields:
| Option | Type | Description |
|---|---|---|
transaction | IDatabaseTransaction | Transaction context for atomic operations |
shouldReturn | boolean | Write methods only - whether to return created/updated data (default: true) |
shouldQueryRange | boolean | find only - return { data, range: { start, end, total } } for pagination |
shouldSkipDefaultFilter | boolean | Bypass the model's default filter (e.g., soft delete) |
force | boolean | updateBy/deleteBy only - allow an empty where (table-wide operation) |
lock | TLockOptions | Row-level locking for reads ({ strength: 'update' }, ...). Requires a transaction; incompatible with include/fields |
log | TRepositoryLogOptions | Per-operation logging ({ use: true, level?: 'info' }) |
// Create without returning data (faster)
await repo.create({
data: { code: 'SETTING', group: 'SYSTEM' },
options: { shouldReturn: false },
});
// Bulk create multiple records
await repo.createAll({
data: [
{ code: 'SETTING_A', group: 'SYSTEM' },
{ code: 'SETTING_B', group: 'SYSTEM' },
],
});
// Query with pagination range
const result = await repo.find({
filter: { limit: 20, skip: 0 },
options: { shouldQueryRange: true }
});
// result = { data: [...], range: { start: 0, end: 19, total: 150 } }Querying with Relations
Use include to fetch related data. The relation name must match what you defined in static relations:
const configWithCreator = await repo.findOne({
filter: {
where: { code: 'APP_NAME' },
include: [{ relation: 'creator' }],
},
});
console.log('Created by:', configWithCreator?.creator.name);Registering Repositories
@repository marks the class. artifacts: AutoArtifacts in the application config registers every decorated repository and datasource at boot, before preConfigure():
// src/application.ts
import AutoArtifacts from '@venizia/ignis-boot/auto';
export const configs: IApplicationConfigs = {
path: { base: '/api', isStrict: true },
artifacts: AutoArtifacts,
};SoftDeletableRepository
For soft-delete patterns, use SoftDeletableRepository which overrides delete operations to set a deletedAt timestamp instead of physically removing records:
import {
BasePostgresEntity,
PostgresIdEnricher,
PostgresTzEnricher,
model,
repository,
SoftDeletableRepository,
} from '@venizia/ignis';
import { pgTable, text, timestamp } from 'drizzle-orm/pg-core';
@model({
settings: {
properties: { hidden: ['deletedAt'] },
query: { filter: { where: { deletedAt: null } } },
},
})
export class Category extends BasePostgresEntity<typeof Category.schema> {
static override schema = pgTable('Category', {
...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }),
...PostgresTzEnricher.generateColumnDefs(),
deletedAt: timestamp('deleted_at', { withTimezone: true }),
name: text('name').notNull(),
});
}
@repository({ dataSource: PostgresDataSource, model: Category })
export class CategoryRepository extends SoftDeletableRepository<typeof Category.schema> {}Delete operations accept shouldHardDelete: true in options to physically remove a row, and soft-deleted records can be restored via restoreById/restoreBy.
Repository Template
import { DefaultCRUDRepository, repository } from '@venizia/ignis';
import { MyModel } from '@/models/entities';
import { PostgresDataSource } from '@/datasources/postgres.datasource';
@repository({ model: MyModel, dataSource: PostgresDataSource })
export class MyModelRepository extends DefaultCRUDRepository<typeof MyModel.schema> {}Advanced Topics
Performance: Core API Optimization
IGNIS automatically optimizes "flat" queries (no relations, no field selection) by using Drizzle's Core API. This provides ~15-20% faster queries for simple reads. The canUseCoreAPI() method on ReadableRepository determines when this optimization applies.
Modular Persistence with Components
Bundle related persistence resources into Components for better organization:
export class UserManagementComponent extends BaseComponent {
override binding() {
this._application.dataSource(PostgresDataSource);
this._application.repository(UserRepository);
this._application.repository(ProfileRepository);
}
}Deep Dive: See Repository Reference for filtering operators, relations, JSON path queries, and array operators.
See Also
Related Concepts:
- Models - Entity definitions used by repositories
- DataSources - Database connections
- Services - Use repositories for data access
- Transactions - Multi-operation consistency
References:
- Repositories API - Complete API reference
- Filter System - Query operators and filtering
- Relations & Includes - Loading related data
- Advanced Features - JSON queries, performance tuning
Best Practices:
- Data Modeling - Repository design patterns
- Performance Optimization - Query optimization
Tutorials:
- Building a CRUD API - Repository examples
- E-commerce API - Advanced queries and relations