Skip to content

Commit

Permalink
Adds missingIf support to hasKeyRelationship
Browse files Browse the repository at this point in the history
  • Loading branch information
arcanis committed Aug 6, 2023
1 parent 1d5db13 commit ab9f045
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -2,7 +2,7 @@
"name": "typanion",
"description": "Simple runtime TypeScript validator library",
"homepage": "https://mael.dev/typanion/",
"version": "3.13.0",
"version": "3.14.0",
"main": "sources/index",
"license": "MIT",
"sideEffects": false,
Expand Down
13 changes: 5 additions & 8 deletions sources/predicates/helperPredicates.ts
Expand Up @@ -248,12 +248,9 @@ const keyRelationships = {
* Create a validator that checks that, when the specified subject property is
* set, the relationship is satisfied.
*/
export function hasKeyRelationship(subject: string, relationship: KeyRelationship, others: string[], {
ignore = [],
}: {
ignore?: any[],
} = {}) {
const skipped = new Set(ignore);
export function hasKeyRelationship(subject: string, relationship: KeyRelationship, others: string[], options?: { ignore?: any[], missingIf?: MissingType }) {
const skipped = new Set(options?.ignore ?? []);
const check = checks[options?.missingIf ?? 'missing'];

const otherSet = new Set(others);
const spec = keyRelationships[relationship];
Expand All @@ -265,12 +262,12 @@ export function hasKeyRelationship(subject: string, relationship: KeyRelationshi
return makeValidator<{[key: string]: unknown}>({
test: (value, state) => {
const keys = new Set(Object.keys(value));
if (!keys.has(subject) || skipped.has(value[subject]))
if (!check(keys, subject, value) || skipped.has(value[subject]))
return true;

const problems: string[] = [];
for (const key of otherSet)
if ((keys.has(key) && !skipped.has(value[key])) !== spec.expect)
if ((check(keys, key, value) && !skipped.has(value[key])) !== spec.expect)
problems.push(key);

if (problems.length >= 1)
Expand Down
11 changes: 11 additions & 0 deletions tests/index.test.ts
Expand Up @@ -508,6 +508,17 @@ const ERROR_TESTS: {
[{foo: 42, bar: false, baz: 42}, [`.: Property "foo" forbids using property "baz"`]],
[{foo: 42, qux: 42}, []],
],
}, {
validator: () => t.cascade(t.isRecord(t.isUnknown()), [t.hasKeyRelationship(`foo`, t.KeyRelationship.Forbids, [`bar`, `baz`], {missingIf: `falsy`})]),
tests: [
[{foo: 42}, []],
[{bar: 42}, []],
[{foo: false, bar: 42}, []],
[{foo: 42, bar: false}, []],
[{foo: 42, bar: false, baz: false}, []],
[{foo: 42, bar: false, baz: 42}, [`.: Property "foo" forbids using property "baz"`]],
[{foo: 42, qux: 42}, []],
],
}, {
validator: () => t.cascade(t.isRecord(t.isUnknown()), [t.hasKeyRelationship(`foo`, t.KeyRelationship.Requires, [`bar`, `baz`])]),
tests: [
Expand Down

0 comments on commit ab9f045

Please sign in to comment.