npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

denwa-nest-shared

v1.2.7

Published

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

Readme

denwa-nest-shared

Общая shared-библиотека для микросервисов и приложений монорепозитория на базе NestJS, GraphQL, OpenAPI (Swagger) и TypeORM.

Возможности

  • Единая валидация схем (ApiValidationProperty): один декоратор объединяет Swagger (@ApiProperty), GraphQL (@Field) и валидацию class-validator (@IsString, @Min, @IsOptional и др.).
  • Контроль доступа к полям (MutableBy, sanitizeDto): ограничение редактирования отдельных полей DTO на основе ролей пользователя.
  • Генератор запросов TypeORM (createQueryData): построение параметров выборки с пагинацией, мультипоиском (ILike), фильтрацией и диапазонами (fromToFields).
  • Гарды и перехватчики ролей (FieldsRolesInterceptor, @CheckFieldsRoles, @Roles, @Public): управление доступом на уровне резолверов и полей GraphQL.
  • OpenAPI Axios клиент (OpenApiAxios): типобезопасный HTTP-клиент на базе схемы OpenAPI.
  • Утилиты: транслитерация (translit, checkTranslit), форматирование телефонов (formatPhone), валидационный пайп (ValidationPipe), интеграция с OpenSearch (OpenSearchCore).

Установка

npm install denwa-nest-shared

Peer Dependencies

Убедитесь, что в вашем сервисе установлены необходимые peer-зависимости:

npm install @nestjs/common @nestjs/graphql @nestjs/swagger class-validator class-transformer graphql typeorm rxjs

Быстрый старт

1. Определение DTO

import { InputType } from '@nestjs/graphql';
import { ApiValidationProperty, MutableBy } from 'denwa-nest-shared';

@InputType()
export class CreateProductDto {
  @ApiValidationProperty({
    type: 'string',
    description: 'Название товара',
    min: 2,
    max: 255,
  })
  nameRU: string;

  @ApiValidationProperty({
    type: 'int',
    min: 0,
    isOptional: true,
  })
  @MutableBy(['super_admin', 'admin'])
  priority?: number;
}

2. Вложенные DTO

Для вложенных объектов передавайте класс DTO через objectType (или swaggerType — для обратной совместимости, включая [SomeDto]). Тогда @Field, @ValidateNested и @Type проставляются автоматически, а ошибочный IsString не эмитится.

import { InputType } from '@nestjs/graphql';
import { ApiValidationProperty } from 'denwa-nest-shared';

@InputType()
class ImageDto {
  @ApiValidationProperty({ type: 'string', max: 256 })
  tempName: string;
}

@InputType()
export class UpdateProductDto {
  @ApiValidationProperty({
    type: 'object',
    objectType: ImageDto,
    isArray: true,
    isOptional: true,
  })
  images?: ImageDto[];
}

3. Фильтрация и поиск с TypeORM

import { createQueryData, encodeCursor, decodeCursor } from 'denwa-nest-shared';
import { Repository } from 'typeorm';

async function getUsers(userRepository: Repository<User>, query: any) {
  const queryData = createQueryData({
    page: query.page ?? 1,
    limit: query.limit ?? 20,
    sortField: 'createdAt',
    sortOrder: 'desc',
    filterType: 'and',
    filter: query.filter,
    search: query.search,
    searchFields: ['name', 'email'],
    // ⚡ Опции для высоконагруженных таблиц (сотни тысяч / миллионы строк):
    cursor: query.cursor, // base64url строка или { id, sortValue, sortValues, order, field }
    sortFields: [         // произвольное число полей сортировки с разными направлениями
      { field: 'priority', order: 'desc' },
      { field: 'createdAt', order: 'asc' },
    ],
    select: ['id'],       // для двухшагового Deferred Join
    extraRow: true,       // take: limit + 1 (проверка следующей страницы без count(*))
    maxPage: 100,         // защита от глубокого OFFSET
  });

  return await userRepository.find(queryData);
}

Сборка и тестирование

# Линтинг
npm run lint

# Форматирование
npm run format

# Тесты
npm test

# Сборка (ESM и CJS)
npm run build

Лицензия

ISC