Skip to content

Commit

Permalink
fix: pick and omit with excluded edges
Browse files Browse the repository at this point in the history
fixes #2097
  • Loading branch information
jquense committed Sep 29, 2023
1 parent e15297b commit 6956ee7
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,17 +419,23 @@ export default class ObjectSchema<
if (this.fields[key]) picked[key] = this.fields[key];
}

return this.setFields<{ [K in TKey]: TIn[K] }, TDefault>(picked);
return this.setFields<{ [K in TKey]: TIn[K] }, TDefault>(
picked,
this._excludedEdges.filter(
([a, b]) => keys.includes(a as TKey) && keys.includes(b as TKey),
),
);
}

omit<TKey extends keyof TIn>(keys: readonly TKey[]) {
const fields = { ...this.fields };
const remaining: TKey[] = [];

for (const key of keys) {
delete fields[key];
for (const key of Object.keys(this.fields) as TKey[]) {
if (keys.includes(key)) continue;
remaining.push(key);
}

return this.setFields<Omit<TIn, TKey>, TDefault>(fields);
return this.pick(remaining);
}

from(from: string, to: keyof TIn, alias?: boolean) {
Expand Down
44 changes: 44 additions & 0 deletions test/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1121,4 +1121,48 @@ describe('Object types', () => {
await inst.omit(['age', 'name']).validate({ color: 'mauve' }),
).toEqual({ color: 'mauve' });
});

it('should pick and omit with excluded edges', async () => {
const inst = object().shape(
{
a1: string().when('a2', {
is: undefined,
then: (schema) => schema.required(),
}),
a2: string().when('a1', {
is: undefined,
then: (schema) => schema.required(),
}),
a3: string().required(),
},
[['a1', 'a2']],
);

expect(
inst.pick(['a1', 'a2']).isValid({
a1: undefined,
a2: 'over9000',
}),
).resolves.toEqual(true);

expect(
inst.pick(['a1', 'a3']).isValid({
a1: 'required',
a3: 'asfasf',
}),
).resolves.toEqual(true);

expect(
inst.omit(['a1', 'a2']).isValid({
a3: 'asfasf',
}),
).resolves.toEqual(true);

expect(
inst.omit(['a1']).isValid({
a1: undefined,
a3: 'asfasf',
}),
).resolves.toEqual(false);
});
});

0 comments on commit 6956ee7

Please sign in to comment.