Skip to content

Commit

Permalink
feat: Add minItems and maxItems checks for arrays. (#224)
Browse files Browse the repository at this point in the history
* feat: Add minItems check for arrays.

* Add maxItems, too.
  • Loading branch information
goloroden committed Nov 25, 2020
1 parent bb7b737 commit 9e70dfa
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/Value.ts
Expand Up @@ -105,6 +105,24 @@ class Value {
break;
}

case 'minItems': {
const { limit } = error.params as Ajv.LimitParams;
const actualCount = failingValue.length;

message = `Array is too short (${actualCount}), minimum ${limit}`;

break;
}

case 'maxItems': {
const { limit } = error.params as Ajv.LimitParams;
const actualCount = failingValue.length;

message = `Array is too long (${actualCount}), maximum ${limit}`;

break;
}

default: {
// Intentionally left blank.
}
Expand Down
34 changes: 34 additions & 0 deletions test/unit/ValueTests.ts
Expand Up @@ -216,6 +216,40 @@ suite('Value', (): void => {
});
}).is.throwing((ex: Error): boolean => ex.message === 'String does not match pattern: ^thenativeweb$ (at value.result).');
});

test('throws an error if an array is too short.', async (): Promise<void> => {
schema = new Value({
type: 'object',
properties: {
result: { type: 'array', minItems: 1 }
},
required: [ 'result' ],
additionalProperties: false
});

assert.that((): void => {
schema.validate({
result: []
});
}).is.throwing((ex: Error): boolean => ex.message === 'Array is too short (0), minimum 1 (at value.result).');
});

test('throws an error if an array is too long.', async (): Promise<void> => {
schema = new Value({
type: 'object',
properties: {
result: { type: 'array', maxItems: 1 }
},
required: [ 'result' ],
additionalProperties: false
});

assert.that((): void => {
schema.validate({
result: [ 23, 42 ]
});
}).is.throwing((ex: Error): boolean => ex.message === 'Array is too long (2), maximum 1 (at value.result).');
});
});
});

Expand Down

0 comments on commit 9e70dfa

Please sign in to comment.