Skip to content

Commit 419e270

Browse files
committed
Connect nestjs container to validator so constraints can be injectable
1 parent 4d81f65 commit 419e270

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/core/validation/validation.module.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { Module } from '@nestjs/common';
22
import { APP_PIPE } from '@nestjs/core';
3+
import { Validator } from 'class-validator';
34
import { ValidationPipe } from './validation.pipe';
45

56
@Module({
67
providers: [
8+
Validator,
79
ValidationPipe,
810
{ provide: APP_PIPE, useExisting: ValidationPipe },
911
],

src/core/validation/validation.pipe.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,34 @@ import {
22
ValidationPipe as BaseValidationPipe,
33
Injectable,
44
} from '@nestjs/common';
5+
import { ModuleRef } from '@nestjs/core';
6+
import { useContainer, ValidatorOptions } from 'class-validator';
57
import { ValidationException } from './validation.exception';
68

79
@Injectable()
810
export class ValidationPipe extends BaseValidationPipe {
9-
constructor() {
11+
constructor(private readonly moduleRef: ModuleRef) {
1012
super({
1113
transform: true,
1214
skipMissingProperties: true,
1315
exceptionFactory: (es) => new ValidationException(es),
1416
});
1517
}
18+
private readonly containerForLib = {
19+
get: (type: any) => {
20+
if (type.name === 'CustomConstraint') {
21+
// Prototype-less constraints. Null to fall back to default, which just calls constructor once.
22+
return null;
23+
}
24+
return this.moduleRef.get(type);
25+
},
26+
};
27+
28+
protected async validate(
29+
object: object,
30+
validatorOptions?: ValidatorOptions,
31+
) {
32+
useContainer(this.containerForLib, { fallback: true });
33+
return await super.validate(object, validatorOptions);
34+
}
1635
}

0 commit comments

Comments
 (0)