Skip to content

ParseEnumPipeOptions

reference
1 min readUpdated

Kind: Interface

Source: packages/common/pipes/parse-enum.pipe.ts

Part of: Common

ParseEnumPipeOptions configures the behavior of NestJS's ParseEnumPipe, which validates that an incoming value belongs to a specified enum. It lets callers control whether a value is optional, which HTTP status code is returned for invalid values, and how validation exceptions are created.

Properties

PropertyType
optionalboolean
errorHttpStatusCodeErrorHttpStatusCode
exceptionFactory(error: string) => any

Diagram

mermaid
graph LR
  A[Incoming request value] --> B[ParseEnumPipe]
  B --> C{Value is optional<br/>and missing?}
  C -->|Yes| D[Return value unchanged]
  C -->|No| E{Matches enum value?}
  E -->|Yes| F[Return validated enum value]
  E -->|No| G[ParseEnumPipeOptions]
  G --> H[errorHttpStatusCode]
  G --> I[exceptionFactory]
  H --> J[Throw validation exception]
  I --> J

Usage

ts
import {
  BadRequestException,
  ParseEnumPipe,
} from '@nestjs/common';

enum UserRole {
  Admin = 'admin',
  Member = 'member',
  Viewer = 'viewer',
}

const enumPipeOptions = {
  optional: true,
  errorHttpStatusCode: 422,
  exceptionFactory: (error: string) =>
    new BadRequestException({
      message: 'Invalid user role',
      details: error,
    }),
};

const rolePipe = new ParseEnumPipe(UserRole, enumPipeOptions);

// Valid: "admin"
// Optional: undefined
// Invalid: "superuser" throws the custom exception

AI Coding Instructions

  • Pass ParseEnumPipeOptions as the second argument when constructing ParseEnumPipe.
  • Set optional: true only when missing or null enum values should bypass enum validation.
  • Use errorHttpStatusCode to align validation failures with the API's HTTP error conventions.
  • Prefer exceptionFactory when your application requires a consistent custom error response shape.
  • Ensure the supplied enum contains the exact values expected from request parameters, query strings, or request bodies.

Was this page helpful?

Download as PDF
ParseEnumPipeOptions — NestJS head-to-head