Skip to content

Commit

Permalink
fix: optional in IsObject with minProperties
Browse files Browse the repository at this point in the history
  • Loading branch information
mdovhopo committed Feb 7, 2022
1 parent e4e8185 commit 59c5c52
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
6 changes: 6 additions & 0 deletions src/decorators/is-object.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ describe('IsObject', () => {
expect(await input(Test, { objectField: false })).toStrictEqual(
Result.err('objectField must be an object')
);
expect(await input(Test, { objectField: undefined })).toStrictEqual(
Result.err('objectField must be an object')
);
expect(await input(Test, { objectField: null })).toStrictEqual(
Result.err('objectField must be an object')
);
});

it('checks maxProperties', async () => {
Expand Down
41 changes: 32 additions & 9 deletions src/decorators/is-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@ import { IsObject as IsObjectCV, ValidateBy } from 'class-validator';

import { compose, noop, PropertyOptions } from '../core';

function validateObjectSize(
obj: Record<string, unknown> | undefined | null,
check: (len: number) => boolean,
optional = true
): boolean {
if (!obj) {
return optional;
}

const { length } = Object.keys(obj);
return check(length);
}

export const IsObject = <T extends Record<string, unknown>>({
message,
minProperties,
Expand All @@ -23,20 +36,30 @@ export const IsObject = <T extends Record<string, unknown>>({
? ValidateBy({
name: 'minProperties',
validator: {
validate: (v) => Object.keys(v).length >= minProperties,
validate: (v) =>
validateObjectSize(
v,
(length) => length >= minProperties,
base.optional || base.nullable
),
defaultMessage: (args) =>
`${args?.property} must have at least ${minProperties} properties`,
},
})
: noop,
maxProperties
? ValidateBy({
name: 'maxProperties',
validator: {
validate: (v) => Object.keys(v).length <= maxProperties,
defaultMessage: (args) =>
`${args?.property} must have at most ${maxProperties} properties`,
},
})
: noop,
name: 'maxProperties',
validator: {
validate: (v) =>
validateObjectSize(
v,
(length) => length <= maxProperties,
base.optional || base.nullable
),
defaultMessage: (args) =>
`${args?.property} must have at most ${maxProperties} properties`,
},
})
: noop
);

0 comments on commit 59c5c52

Please sign in to comment.