#How to use CustomPipe without instantiating the class

6 messages · Page 1 of 1 (latest)

void vector
#
import { BadRequestException, Injectable, PipeTransform } from "@nestjs/common";
import { ParseObjectIdPipe } from "@nestjs/mongoose";
import { Types } from "mongoose";

@Injectable()
export class ParseObjectIdPipeLocal
  implements PipeTransform<unknown, Types.ObjectId>
{
  private readonly optional: boolean;

  constructor({ optional = false }: { optional?: boolean } = {}) {
    this.optional = optional;
  }

  transform(value: unknown): Types.ObjectId {
    if (this.optional && value === undefined) {
      return undefined as unknown as Types.ObjectId;
    }

    if (typeof value !== "string") {
      throw new BadRequestException("Value is required and must be a string.");
    }

    return new ParseObjectIdPipe().transform(value);
  }
}
#

I'm forced to use it like this

  @Get(":documentTypeId")
  async findById(
    @Param("documentTypeId", new ParseObjectIdPipeLocal())
    documentTypeId: string,
  ): Promise<PublicDocumentTypeResponseDto> {
    return await this.documentTypesService.findById(documentTypeId);
  }
#

But I wanted to be able to use it like this, when no constructor field was needed.

  @Get(":documentTypeId")
  async findById(
    @Param("documentTypeId", ParseObjectIdPipeLocal)
    documentTypeId: string,
  ): Promise<PublicDocumentTypeResponseDto> {
    return await this.documentTypesService.findById(documentTypeId);
  }
#

By the way, this only happens if I have a constructor. If I remove the constructor, it doesn't force me to have the instance, but I need the constructor to have the Optional.

wide merlin
#

that's the way

rapid lanternBOT
#

This post has been marked as resolved. ✅
Please read through the conversation and resolution, if you are having the same issue.
If you were the original author of the post and the issue is still fresh (within a few days) and you are still have having trouble, continue to reply here. If you are not the original author of the post or the post has aged, start a new thread linking this one as relevant to your problem, providing as much additional information as possible.