Skip to content

Commit

Permalink
fix: fix parsing nested object
Browse files Browse the repository at this point in the history
  • Loading branch information
ASafaeirad committed Jan 7, 2024
1 parent bb70f4c commit 74bc50a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
12 changes: 12 additions & 0 deletions src/Schema/ObjectSchema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,16 @@ describe('Object Schema', () => {

expect(() => schema.validate()).not.toThrow();
});

it('should parse nested values', () => {
const schema = new ObjectSchema<{ foo: string }>({
foo: new NumberSchema(),
});
schema.key = 'key';
schema.setValue({ foo: '3000' });

expect(() => schema.validate()).not.toThrow();

expect(schema.value?.foo).toBeTypeOf('number');
});
});
31 changes: 25 additions & 6 deletions src/Schema/ObjectSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,38 @@ class ObjectGuard implements Guard<Record<string, Schema>> {
}
}

export class ObjectSchema<TInput = any> extends Schema<
TInput,
TInput,
boolean
> {
export class ObjectSchema<
TInput extends Record<string, unknown> = any,
> extends Schema<TInput, TInput, boolean> {
protected type = 'object';

constructor(schema: Record<string, Schema<any, any, boolean>>) {
constructor(private schema: Record<string, Schema<any, any, boolean>>) {
super({
typeConstructor: x => x,
initialGuards: [new TypeGuard('object')],
});
this.required();
this.guards.push(new ObjectGuard(schema));
}

public override setValue(input?: TInput) {
this.input = input;

if (typeof input !== 'object') {
this.value = input;
} else {
this.value = Object.keys(input).reduce((acc, key) => {
const schema = this.schema[key];

if (!schema) return acc;

schema.setValue(input[key]);
// @ts-expect-error It's hard
acc[key] = schema.parse();
return acc;
}, {}) as TInput;
}

return this;
}
}

0 comments on commit 74bc50a

Please sign in to comment.