Skip to content

Commit

Permalink
fix(class-validator): return instance unless rawValues is set (#617)
Browse files Browse the repository at this point in the history
  • Loading branch information
perebusquets authored Aug 17, 2023
1 parent 3519701 commit 4882173
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
41 changes: 41 additions & 0 deletions class-validator/src/__tests__/class-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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);
});
5 changes: 4 additions & 1 deletion class-validator/src/class-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,8 @@ export const classValidatorResolver: Resolver =

options.shouldUseNativeValidation && validateFieldsNatively({}, options);

return { values, errors: {} };
return {
values: resolverOptions.rawValues ? values : data,
errors: {},
};
};

0 comments on commit 4882173

Please sign in to comment.