Naalya Handbook

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

DoorUse forReturns
findAll(options?)straightforward readsT[]
createQueryBuilder(alias)dynamic joins / optional filtersSelectQueryBuilder<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:

libs/shared/src/database/base.repository.ts
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.

apps/server/src/app/transaction/transaction.service.ts
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:

OptionMeaning
afterId / beforeIdUUID cursors; forward / backward; mutually exclusive
limitpage size, default 10
scopeCASL permission where from the caller: see RBAC & Scopes
searchColumns + searchmulti-word ILIKE; term split on whitespace, each word must match ≥1 column
findOptionsstandard where and relations
cursorFielddefault 'id'
dateFielddefault 'createdAt'
startDate / endDatedate-range filter
sortPrefixextra 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

libs/shared/src/database/pagination/cursor-pagination.types.ts
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:

libs/shared/src/database/pagination/cursor-pagination.dto.ts
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:

apps/.../job-application/job-application-list-query.dto.ts
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

On this page