1.4.3 • Published 4 months ago

@stickelinnovation/nestjs-prisma-query v1.4.3

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

Prisma Query Decorator for NestJS

This library provides a powerful and configurable PrismaQuery decorator for NestJS that allows dynamic query parsing for REST endpoints using Prisma ORM.

šŸ“Œ Features

āœ… Configurable global settings (sensitiveFields, excludeKeys, forbiddenKeys, requestFields)
āœ… Automatically includes request-based fields (e.g., userId, accountId)
āœ… Supports filtering, ordering, and relations
āœ… Validation using DTOs
āœ… Paginator for findMany requests
āœ… Generate OpenApi (Swagger) docs

Example request: GET /endpoint?filter.category=electronics&filter.price$gte:100


šŸš€ Installation

npm install @stickelinnovation/nestjs-prisma-query
# or
pnpm add @stickelinnovation/nestjs-prisma-query
# or
yarn add @stickelinnovation/nestjs-prisma-query

šŸ“ Peer Dependencies

Ensure you have the following peer dependencies installed:

  • @nestjs/common
  • @nestjs/core
  • @prisma/client

šŸ› ļø Configuration

You can configure the query service globally in your main.ts file before starting your NestJS application.

Additionally you can import the usePrismaQueryExceptionFilter to enhance the exception logging. You can use the the exception filter besides the PrismaClientExceptionFilter from nestjs-prisma.

Example Configuration

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {
  PrismaQueryService,
  usePrismaQueryExceptionFilter,
} from '@stickelinnovation/nestjs-prisma-query';
// import { PrismaClientExceptionFilter } from 'nestjs-prisma';

async function bootstrap() {
  PrismaQueryService.configure({
    sensitiveFields: ['password', 'ssn'], // Prevents filtering/sorting by these fields
    excludeKeys: ['internalNotes'], // Keys that will be removed from the query
    requestFields: ['userId', 'accountId'], // Automatically added to Prisma `where` clause
  });

  const app = await NestFactory.create(AppModule);
  await app.listen(3000);

  // app.useGlobalFilters(new PrismaClientExceptionFilter(httpAdapter));

  usePrismaQueryExceptionFilter(app); // Prisma Query Exception Filter
}

bootstrap();

šŸ“š Usage in Controllers

Basic Example

Use the PrismaQuery decorator in your controller to parse Prisma queries dynamically.

import { Controller, Get } from '@nestjs/common';
import { PrismaQuery } from '@stickelinnovation/nestjs-prisma-query';
import { MyDto } from './dto/my.dto';
import { MyService } from './my.service';

@Controller('endpoint')
export class ItemController {
  constructor(private readonly myService: MyService) {}

  @Get()
  async getEndpoint(@PrismaQuery({ dto: MyDto, fieldTypeMap: {} }) prismaArgs) {
    return this.myService.findMany(prismaArgs);
  }
}

šŸ“Œ Config Options Explained

šŸ‘‰ sensitiveFields

Sensitive fields cannot be used in filters (where) or sorting (orderBy).
Example:

PrismaQueryService.configure({
  sensitiveFields: ['password', 'apiKey'],
});

🚫 Blocked Example:

GET /endpoint?filter.password=1234

This request will return an error because password is a sensitive field.


šŸ‘‰ excludeKeys

These keys will be removed from the query before processing.
Example:

PrismaQueryService.configure({
  excludeKeys: ['internalNotes'],
});

āŒ Removed Example:

GET /endpoint?internalNotes=something&name=Item1
  • The query { internalNotes: 'something', name: 'Item1' }
  • Becomes { name: 'Item1' } (internalNotes is excluded)

šŸ‘‰ forbiddenKeys

Forbidden keys cannot be present in the query at all. If found, an error is thrown.
Example:

PrismaQueryService.configure({
  forbiddenKeys: ['revalidate'],
});

🚫 Blocked Example:

GET /endpoint?revalidate=true

This request will return an error because revalidate is forbidden.


šŸ‘‰ requestFields

Fields that are automatically added to the where clause from the request object.
Example:

PrismaQueryService.configure({
  requestFields: ['userId', 'accountId'],
});

āœ… Automatic Filtering

If the request contains userId=5:

GET /endpoint?category=books

This will automatically transform into:

where: {
  category: 'books',
  userId: 5,  // Auto-added from request
}

šŸ“ž Full Example with Prisma Service

DTO / Entity for Validation

import { Prisma } from '@prisma/client';
import {
  applySwaggerProperties,
  PrismaQueryDto,
} from '@stickelinnovation/nestjs-prisma-query';
import { favoriteFieldTypeMap } from 'src/favorites/entities/favorite.entity';

export class LikeQueryDto extends PrismaQueryDto<Prisma.LikeFindManyArgs> {
  constructor() {
    super();
  }

  static applySwaggerProperties() {
    applySwaggerProperties(LikeQueryDto, likeFieldTypeMap);
  }
}

LikeQueryDto.applySwaggerProperties();
import { generateFieldTypeMap } from '@stickelinnovation/nestjs-prisma-query';

export class LikeEntity {
  id: number;
  createdAt: Date;
  video?: VideoEntity;
  serie?: SerieEntity;

  constructor() {
    this.id = 0;
    this.createdAt = new Date();
    this.video = new VideoEntity();
    this.serie = new SerieEntity();
  }
}

export const likeFieldTypeMap = generateFieldTypeMap(LikeEntity);

Controller

import {
  PrismaQuery,
  PaginationResultDto,
} from '@stickelinnovation/nestjs-prisma-query';

export class LikesController {
  constructor(private readonly likesService: LikesService) {}

  @Get('video')
  @ApiOperation({ summary: 'Get all video like entries' })
  @ApiOkResponse({ type: PaginationResultDto<LikeEntity>, isArray: false })
  @ApiQuery({ type: LikeQueryDto })
  @ApiQuery({
    name: 'revalidate',
    required: false,
    type: Boolean,
    example: false,
  })
  findAllVideoLikes(
    @PrismaQuery({
      fieldTypeMap: likeFieldTypeMap,
      dto: LikeQueryDto,
      forbiddenKeys: [], //optional
      sensitiveFields: ['userId'], //optional
      excludeKeys: ['revalidate'], //optional
    })
    query: Prisma.LikeFindManyArgs,
    @Query('revalidate', new DefaultValuePipe(true), ParseBoolPipe)
    revalidate: boolean = true,
  ) {
    return this.likesService.findAllVideoLikes(query, revalidate);
  }
}

Service

import { paginate } from '@stickelinnovation/nestjs-prisma-query';

async findAllVideoLikes(
    query: Prisma.LikeFindManyArgs,
  ) {
    try {
      const likes = await paginate(this.prisma.like, {
        ...query,
      });

      return likes;
    } catch (error) {
      handlePrismaError(error);
    }
  }

šŸŽÆ Config Options Use Cases

FeatureUse Case
sensitiveFieldsPrevents exposing or filtering fields like password, ssn
excludeKeysRemoves unnecessary fields like internalNotes, metaData
forbiddenKeysBlocks harmful query parameters like revalidate, debugMode
requestFieldsEnsures userId, accountId are always included in filtering

šŸ“Œ Query Operators Explained

GET /endpoint?filter.[fieldName]=[value]&filter.[fieldName]$[operator]:[value]

Filtering (where)

The filter parameter allows you to dynamically apply Prisma where conditions.

Example:

GET /endpoint?filter.category=electronics&filter.price$gte:100

Prisma equivalent:

where: {
  category: 'electronics',
  price: { gte: 100 },
}

Supported Operators:

OperatorDescriptionExample Usage
$eqEqualsfilter.videoCrn=$eq:123
$neNot equalsfilter.videoCrn=$ne:123
$ltLess thanfilter.createdAt=$lt:2024-01-01
$lteLess than or equal tofilter.createdAt=$lte:2024-01-01
$gtGreater thanfilter.createdAt=$gt:2024-01-01
$gteGreater than or equal tofilter.createdAt=$gte:2024-01-01
$containsContains (for text search)filter.name=$contains:demo
$startsWithStarts withfilter.name=$startsWith:demo
$endsWithEnds withfilter.name=$endsWith:demo
$inIn a list of valuesfilter.videoCrn=$in:123,456
$notInNot in a list of valuesfilter.videoCrn=$notIn:123,456

You can also combine operators with logical operators, such as AND, OR, and NOT.

Logical AND

$AND=filter.{filterName}=$endsWith:{filterValue}|filter.{filterName}=$endsWith:{filterValue}

Logical OR

$OR=filter.{filterName}=$endsWith:{filterValue}|filter.{filterName}=$endsWith:{filterValue}

Logical NOT $NOT=filter.{filterName}=$endsWith:{filterValue}


Sorting (orderBy)

The orderBy parameter allows sorting results.

Example:

GET /endpoint?orderBy=price:asc&orderBy=createdAt:desc

Prisma equivalent:

orderBy: [{ price: 'asc' }, { createdAt: 'desc' }];

Pagination (take, skip)

Pagination allows limiting results and fetching subsequent pages.

Example:

GET /endpoint?take=10&skip=20

Prisma equivalent:

take: 10,
skip: 20

Relations (include, select)

You can include or select related models.

Example:

GET /endpoint?include=category,genre&select=name

Prisma equivalent:

include: { category: true, genre: true },
select: { name: true }

Distinct (distinct)

You can specify which fields should be distinct.

Example:

GET /endpoint?distinct=name

Prisma equivalent:

distinct: ['name'];

🐟 License

MIT License Ā© 2025 - Stickel Innovation UG (Jonas Stickel)


1.4.3

4 months ago

1.4.2

4 months ago

1.4.1

4 months ago

1.4.0

5 months ago

1.3.0

5 months ago

1.2.0

5 months ago

1.1.0

5 months ago

1.0.4

5 months ago

1.0.3

5 months ago

1.0.2

5 months ago

1.0.1

5 months ago

1.0.0

5 months ago