Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { plainToInstance, ClassConstructor } from 'class-transformer';
import 'reflect-metadata';
import { PARAMTYPES_METADATA } from '@nestjs/common/constants';

@Injectable()
export class TransformEnumInterceptor implements NestInterceptor {
Expand Down Expand Up @@ -44,19 +45,15 @@ export class TransformEnumInterceptor implements NestInterceptor {
context: ExecutionContext,
): ClassConstructor<any> | null {
const handler = context.getHandler();
const controller = context.getClass();
const prototype = context.getClass().prototype;

// Get the parameter types of the route handler
const routeArgs = Reflect.getMetadata(
'design:paramtypes',
controller.prototype,
handler.name,
);
const paramTypes =
Reflect.getMetadata(PARAMTYPES_METADATA, prototype, handler.name) ?? [];

// Return the first parameter's constructor if the handler has a class (DTO)
return routeArgs && routeArgs.length > 0
? (routeArgs[0] as ClassConstructor<any>)
: null;
return (
paramTypes.find((type: unknown) => this.isTransformableClass(type)) ??
null
);
}

private transformEnums(
Expand Down Expand Up @@ -113,4 +110,18 @@ export class TransformEnumInterceptor implements NestInterceptor {
}
return bodyOrQuery;
}

private isTransformableClass(type: unknown): type is ClassConstructor<any> {
if (typeof type !== 'function') {
return false;
}

return (
type !== String &&
type !== Boolean &&
type !== Number &&
type !== Array &&
type !== Object
);
}
}
Loading