Skip to content

Commit

Permalink
feat: Add StrictEnumField with better validation (#222)
Browse files Browse the repository at this point in the history
  • Loading branch information
wschurman committed May 2, 2024
1 parent 3377129 commit 8753252
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
15 changes: 15 additions & 0 deletions packages/entity/src/EntityFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,18 @@ export class EnumField extends EntityFieldDefinition<string | number> {
return typeof value === 'number' || typeof value === 'string';
}
}

/**
* EntityFieldDefinition for a enum column with a strict typescript enum type.
*/
export class StrictEnumField<T extends object> extends EnumField {
private readonly enum: T;
constructor(options: ConstructorParameters<typeof EnumField>[0] & { enum: T }) {
super(options);
this.enum = options.enum;
}

protected override validateInputValueInternal(value: string | number): boolean {
return super.validateInputValueInternal(value) && Object.values(this.enum).includes(value);
}
}
12 changes: 12 additions & 0 deletions packages/entity/src/__tests__/EntityFields-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
StringArrayField,
JSONObjectField,
EnumField,
StrictEnumField,
} from '../EntityFields';
import describeFieldTestCase from '../utils/testing/describeFieldTestCase';

Expand Down Expand Up @@ -75,3 +76,14 @@ describeFieldTestCase(
);
describeFieldTestCase(new JSONObjectField({ columnName: 'wat' }), [{}], [true, 'hello']);
describeFieldTestCase(new EnumField({ columnName: 'wat' }), ['hello', 1], [true]);

enum TestEnum {
HELLO = 'world',
WHO = 'wat',
}

describeFieldTestCase(
new StrictEnumField({ columnName: 'wat', enum: TestEnum }),
[TestEnum.HELLO, TestEnum.WHO, 'world'],
['what', 1, true]
);
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Entity from '../../Entity';
import { EntityCompanionDefinition } from '../../EntityCompanionProvider';
import EntityConfiguration from '../../EntityConfiguration';
import { UUIDField, EnumField, StringField } from '../../EntityFields';
import { UUIDField, StringField, StrictEnumField } from '../../EntityFields';
import EntityPrivacyPolicy from '../../EntityPrivacyPolicy';
import ViewerContext from '../../ViewerContext';
import { successfulResults, failedResults } from '../../entityUtils';
Expand Down Expand Up @@ -98,8 +98,9 @@ const testEntityConfiguration = new EntityConfiguration<TestFields>({
common_other_field: new StringField({
columnName: 'common_other_field',
}),
entity_type: new EnumField({
entity_type: new StrictEnumField({
columnName: 'entity_type',
enum: EntityType,
}),
},
databaseAdapterFlavor: 'postgres',
Expand Down

0 comments on commit 8753252

Please sign in to comment.