Skip to content

Commit

Permalink
fix(type): correctly report invalid date types
Browse files Browse the repository at this point in the history
fixes #412
  • Loading branch information
marcj committed Feb 17, 2023
1 parent 0f4cf65 commit 10868e4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/type/src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1987,7 +1987,7 @@ export class Serializer {

// when an object with primary key is given e.g. {id: 1} we treat it as
// reference and assign an instance of Reference to the property.
const l: string[] = [`getObjectKeysSize(${state.accessor}) === ${reflection.getPrimaries().length}`];
const l: string[] = [`${reflection.getPrimaries().length} > 0 && getObjectKeysSize(${state.accessor}) === ${reflection.getPrimaries().length}`];
for (const pk of reflection.getPrimaries()) {
l.push(`${JSON.stringify(pk.name)} in ${state.accessor}`);
}
Expand Down Expand Up @@ -2139,7 +2139,7 @@ export class Serializer {

this.typeGuards.getRegistry(1).registerClass(Set, typeGuardClassSet);
this.typeGuards.getRegistry(1).registerClass(Map, typeGuardClassMap);
this.typeGuards.getRegistry(1).registerClass(Date, (type, state) => state.addSetter(`${state.accessor} instanceof Date`));
this.typeGuards.getRegistry(1).registerClass(Date, (type, state) => state.addSetterAndReportErrorIfInvalid('type', 'No a Date', `${state.accessor} instanceof Date`));

This comment has been minimized.

Copy link
@marcj

marcj Feb 20, 2023

Author Member

uff, thanks!

This comment has been minimized.

Copy link
@marcj

marcj Feb 20, 2023

Author Member

Fixed in 2a79e5a

this.typeGuards.getRegistry(0.5).registerClass(Date, (type, state) => {
state.addSetter(`'string' === typeof ${state.accessor} && new Date(${state.accessor}).toString() !== 'Invalid Date'`);
});
Expand Down
8 changes: 8 additions & 0 deletions packages/type/tests/validation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,3 +290,11 @@ test('class with statics', () => {
expect(validate<PilotId>({value: 34})).toEqual([]);
expect(validate<PilotId>({value: '33'})).toEqual([{code: 'type', message: 'Not a number', path: 'value'}]);
});

test('date', () => {
class Account {
public name!: string;
public createdAt!: Date;
}
expect(validate<Account>({name: "jack", createdAt: 'asd'})).toEqual([{code: 'type', message: 'No a Date', path: 'createdAt'}]);
});

0 comments on commit 10868e4

Please sign in to comment.