Skip to content

denwa-nest-shared

Shared NestJS module for DTO validation, RBAC, TypeORM query building, and OpenAPI client

data-access-typeorm

core
182 linesSource

Generating complex TypeORM FindOptions using the createQueryData helper. Standardizes filtering, ILike searching, range mapping (fromToFields), and pagination.

TypeORM Query Generation

Use this skill to transform frontend filter and search parameters into standard TypeORM FindOptions. This is the preferred way to build all data-fetching logic in projects using this library.

Setup

Initialize a repository query using createQueryData.

ts
import { createQueryData } from 'denwa-nest-shared';
import { Repository } from 'typeorm';

async function findUsers(repository: Repository<User>, args: GetUsersArgs) {
  const queryData = createQueryData({
    page: args.page ?? 1,
    limit: args.limit ?? 20,
    sortField: args.sortField ?? 'createdAt',
    sortOrder: args.sortOrder ?? 'desc',
    filterType: 'and',
    filter: args.filter, // Object with direct matches
    search: args.search, // Multi-field string or object for ILike search
  });

  return await repository.findAndCount(queryData);
}

Core Patterns

Range Mapping (fromToFields)

Map specific "start" and "end" fields to a single column range (e.g. priceStart and priceEnd map to price).

ts
const queryData = createQueryData({
  page: 1,
  limit: 20,
  sortField: 'createdAt',
  sortOrder: 'desc',
  filterType: 'and',
  filter: { minPrice: 100, maxPrice: 500 },
  fromToFields: [
    {
      fromFieldName: 'minPrice',
      toFieldName: 'maxPrice',
      originalFieldName: 'price',
    },
  ],
});
// Result includes: where: { price: And(MoreThanOrEqual(100), LessThanOrEqual(500)) }

Array Overlap Filtering

Search for entities where an array column contains any of the provided values.

ts
const queryData = createQueryData({
  page: 1,
  limit: 20,
  sortField: 'createdAt',
  sortOrder: 'desc',
  filterType: 'and',
  filter: { categoryIds: [1, 2, 3] },
  oneEntryArrayFields: [{ key: 'categoryIds', originalKey: 'categories' }],
});
// Uses ArrayOverlap for those fields

Combined Search and Filter

createQueryData supports both strict filtering and fuzzy searching.

ts
const queryData = createQueryData({
  page: 1,
  limit: 20,
  sortField: 'createdAt',
  sortOrder: 'desc',
  filterType: 'and',
  filter: { isActive: true },
  search: { firstName: 'John', lastName: 'Doe' },
  searchType: 'or', // Default: searches for firstName OR lastName matching the terms
});

Common Mistakes

CRITICAL Manually Building QueryBuilders

Wrong:

ts
const qb = repository.createQueryBuilder('user');
if (filter.name) {
  qb.andWhere('user.name ILIKE :name', { name: `%${filter.name}%` });
}

Correct:

ts
const queryData = createQueryData({ search: { name: filter.name } });
const results = await repository.find(queryData);

Falling back to raw QueryBuilders for standard filtering and searching avoids the library's optimized range, overlap, and pagination logic. Always use createQueryData.

Source: maintainer interview

HIGH Incorrect fromToFields Mapping

Wrong:

ts
createQueryData({
  filter: { ageFrom: 18, ageTo: 99 },
  fromToFields: [
    {
      fromFieldName: 'ageFrom',
      toFieldName: 'ageTo',
      originalFieldName: 'id', // Mismatched field name
    },
  ],
});

Correct:

ts
createQueryData({
  filter: { ageFrom: 18, ageTo: 99 },
  fromToFields: [
    {
      fromFieldName: 'ageFrom',
      toFieldName: 'ageTo',
      originalFieldName: 'age',
    },
  ],
});

The originalFieldName must exactly match the property name on your Entity.

Source: Denwa799/nest-shared:src/lib.ts:454

MEDIUM Ignoring searchType Default

Wrong:

ts
// Assuming this will search for users who match BOTH critera
const queryData = createQueryData({
  search: { firstName: 'John', email: 'test@' },
});

Correct:

ts
const queryData = createQueryData({
  search: { firstName: 'John', email: 'test@' },
  searchType: 'and',
});

By default, searchType is 'or'. If you need strict matching across multiple search fields, you must explicitly set it to 'and'.

Source: Denwa799/nest-shared:src/lib.ts:479