Querying and pagination
How list endpoints read data, extend the query per request, and page results with the cursor-based pagination helper.
The canonical list/read surface on BaseRepository<T>. Every read here merges the current tenant's schoolId into the where for you: see Multi-Tenancy. Year-scoped lists additionally require an explicit campusAcademicYearId in the query DTO: that filter is yours to apply, never auto-merged; see Request Scoping.
Two ways to read a list
| Door | Use for | Returns |
|---|---|---|
findAll(options?) | straightforward reads | T[] |
createQueryBuilder(alias) | dynamic joins / optional filters | SelectQueryBuilder<T> |
Both auto-merge the tenant predicate.
Find options
findAll takes FindManyOptions<T>: the per-request extend surface. Pass where, relations, select, order inline:
const rows = await this.repo.findAll({
where: { status: 'active' },
relations: { profile: true },
select: { id: true, firstName: true },
order: { createdAt: 'DESC' },
});Same shape works across findOne, findById, findOneWhere, findAndCount, count, exists. The repo's scopeManyOptions rewrites where to add the tenant predicate, then passes through.
Query builder
createQueryBuilder(alias) returns a normal TypeORM builder with the tenant filter already andWhere-d on, and .where rewired to .andWhere:
qb.where = ((where, params) => boundAndWhere(where, params)) as typeof qb.where;TypeORM's real .where() resets all conditions: the rewire stops a later call site from silently dropping the schoolId predicate.
Cursor pagination
repo.cursorPaginate(alias, options) builds a tenant-injected query builder and pages it with a cursor. Service collection methods that page are named list, not findAll.
async list(query: TransactionListQueryDto) {
const scope = this.permissionScope.getScope<TransactionEntity>(
Action.LIST,
Resource.TRANSACTION,
);
return this.transactionRepository.cursorPaginate('tn', {
...query,
scope: scope ?? undefined,
searchColumns: TransactionService.SEARCH_COLUMNS,
});
}The DTO field names line up with the options, so ...query does most of the wiring. The options object:
| Option | Meaning |
|---|---|
afterId / beforeId | UUID cursors; forward / backward; mutually exclusive |
limit | page size, default 10 |
scope | CASL permission where from the caller: see RBAC & Scopes |
searchColumns + search | multi-word ILIKE; term split on whitespace, each word must match ≥1 column |
findOptions | standard where and relations |
cursorField | default 'id' |
dateField | default 'createdAt' |
startDate / endDate | date-range filter |
sortPrefix | extra leading ORDER BY keys for a stable composite cursor |
findOptions.select, where, and relations are applied. select always keeps id and the order fields. skip, take, and order inside findOptions are not read.
Mechanics, re-read in cursor-pagination.ts at API fbb63d5178bcfe171292daebb19b6cbdac025a44. A missing, non-finite, or non-positive limit becomes 10. A larger value is floored and capped at 100. Order is sortPrefix, then dateField descending (default createdAt), then cursorField descending (default id). A repeated field keeps the first direction. Both cursors throw Cannot provide both afterId and beforeId. A filters value with no filterFields allow-list throws This list does not support filters. A cursor property that is not a column throws Cursor field plus the name plus is not a column on the entity name. The count query runs before the cursor predicate. The page query takes limit + 1. An empty page after a cursor throws Unknown cursor only when that cursor row does not exist. At API main d0fbb403 the paginator takes cursorScope. The cursor subquery and that exists check both require those fields. Department members pass departmentId, so a cursor from another department is Unknown cursor. The Hub membership panel opens with the table's page query, so it reads that same page. cursor-pagination.ts and department-x-staff.service.ts were read. The pagination test was not run. A real cursor at the end of the list returns an empty page. nextCursor is the last row’s cursor field when another page exists, otherwise null. previousCursor is the first row’s cursor field when a cursor was used and the page is not empty, otherwise null. Backward paging flips the order, then reverses the rows. Search splits on whitespace, escapes \, %, and _, and requires every word to match at least one search column with ILIKE. endDate is moved to 23:59:59.999 with setHours before the comparison. No list was called.
On API staging 6308a8a1 (not on main d0fbb403), cursorPaginate and applySearchAndDateFilters refuse a list option that is not a bare name. The name must be a letter or underscore, then letters, digits, or underscores. The check covers cursorField, dateField (default createdAt), each sortPrefix field, each searchColumns entry, and findOptions.select when that value is an array. A scope that is a string is refused the same way. The error is 400 Invalid list option. cursor-pagination.ts was read at that commit. The new pagination test was not run. A merge to staging is not a running deploy.
What you get back
export interface CursorPaginatedResult<T> {
data: T[];
totalCount: number;
hasMore: boolean;
nextCursor: string | null;
previousCursor: string | null;
}Controllers document this in OpenAPI with the CursorPaginatedResponseDto(ItemDto) mixin, which wraps the item DTO in the paginated envelope.
The query DTO
List request DTOs extend CursorPaginationQueryDto from @app/shared, it carries search, both cursors, limit, and the date range, already validated:
export class CursorPaginationQueryDto {
@IsOptional() @IsString() search?: string;
@IsOptional() @IsUUID() afterId?: string;
@IsOptional() @IsUUID() beforeId?: string;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100)
limit?: number; // default 10, coerced from the query string
}The same file also declares filters (a JSON string, max 4000 characters; the description names operators eq and in), startDate, and endDate. @Type(() => Number) on limit coerces the query-string value before @Min/@Max run: see DTOs & Validation. A feature adds its own filters by extending the base:
export class JobApplicationListQueryDto extends CursorPaginationQueryDto {
@IsOptional() @IsUUID() vacancyId?: string;
@IsOptional() @IsEnum(JobApplicationStatus) status?: JobApplicationStatus;
}The service decides which extra fields map to cursorPaginate options and which become findOptions.where.
cursorField, dateField, and sortPrefix take entity property names (createdAt, staffId). When a cursor id is present, a name that is not a column throws Cursor field plus that name plus is not a column on the entity. The no-cursor order-by path was not exercised.
Why cursors
An offset is a position, and positions drift: insert or delete a row on page one while a user reads page two and every later offset shifts, they see a row twice or skip one. A cursor anchors on an exact record, so the next page stays correct under concurrent writes.
Where to go next
Multi-Tenancy
How the schoolId predicate gets merged into every read.
DTOs & Validation
How query DTOs are coerced and validated before the service sees them.
RBAC & Scopes
Where the CASL scope passed into cursorPaginate comes from.
API Conventions
The response envelopes and controller patterns lists feed into.
DTOs and validation
How request and response DTOs are decorated to validate input and document the API, and what the global pipe does and does not do.
Error handling and logging
Services throw HttpExceptions, one global filter turns them into the error envelope, and pino writes one masked line per request.