From 4882173457223a45464032e7bfd826da2d94b709 Mon Sep 17 00:00:00 2001 From: Pere Busquets <43433557+perebusquets@users.noreply.github.com> Date: Thu, 17 Aug 2023 15:53:19 +0200 Subject: [PATCH] fix(class-validator): return instance unless rawValues is set (#617) --- .../src/__tests__/class-validator.ts | 41 +++++++++++++++++++ class-validator/src/class-validator.ts | 5 ++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/class-validator/src/__tests__/class-validator.ts b/class-validator/src/__tests__/class-validator.ts index 45d8ac07..6516c51e 100644 --- a/class-validator/src/__tests__/class-validator.ts +++ b/class-validator/src/__tests__/class-validator.ts @@ -20,6 +20,19 @@ describe('classValidatorResolver', () => { expect(schemaSpy).toHaveBeenCalledTimes(1); expect(schemaSyncSpy).not.toHaveBeenCalled(); expect(result).toEqual({ errors: {}, values: validData }); + expect(result.values).toBeInstanceOf(Schema); + }); + + it('should return values as a raw object from classValidatorResolver when `rawValues` set to true', async () => { + const result = await classValidatorResolver(Schema, undefined, { + rawValues: true, + })(validData, undefined, { + fields, + shouldUseNativeValidation, + }); + + expect(result).toEqual({ errors: {}, values: validData }); + expect(result.values).not.toBeInstanceOf(Schema); }); it('should return values from classValidatorResolver with `mode: sync` when validation pass', async () => { @@ -33,6 +46,7 @@ describe('classValidatorResolver', () => { expect(validateSyncSpy).toHaveBeenCalledTimes(1); expect(validateSpy).not.toHaveBeenCalled(); expect(result).toEqual({ errors: {}, values: validData }); + expect(result.values).toBeInstanceOf(Schema); }); it('should return a single error from classValidatorResolver when validation fails', async () => { @@ -145,3 +159,30 @@ it('validate data with validator option', async () => { expect(result).toMatchSnapshot(); }); + +it('should return from classValidatorResolver with `excludeExtraneousValues` set to true', async () => { + class SchemaTest { + @Expose() + @IsNumber({}, { message: `Must be a number`, always: true }) + random: number; + } + + const result = await classValidatorResolver(SchemaTest, { + transformer: { + excludeExtraneousValues: true, + }, + })( + { + random: 10, + extraneousField: true, + }, + undefined, + { + fields, + shouldUseNativeValidation, + }, + ); + + expect(result).toEqual({ errors: {}, values: { random: 10 } }); + expect(result.values).toBeInstanceOf(SchemaTest); +}); diff --git a/class-validator/src/class-validator.ts b/class-validator/src/class-validator.ts index 5cd716e6..4f9464b6 100644 --- a/class-validator/src/class-validator.ts +++ b/class-validator/src/class-validator.ts @@ -60,5 +60,8 @@ export const classValidatorResolver: Resolver = options.shouldUseNativeValidation && validateFieldsNatively({}, options); - return { values, errors: {} }; + return { + values: resolverOptions.rawValues ? values : data, + errors: {}, + }; };