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
| Property | Type |
|---|---|
optional | boolean |
errorHttpStatusCode | ErrorHttpStatusCode |
exceptionFactory | (error: string) => any |
Diagram
mermaidgraph 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
tsimport {
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
ParseEnumPipeOptionsas the second argument when constructingParseEnumPipe. - Set
optional: trueonly when missing ornullenum values should bypass enum validation. - Use
errorHttpStatusCodeto align validation failures with the API's HTTP error conventions. - Prefer
exceptionFactorywhen 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?