Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions packages/entity/src/EntityFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,18 +129,28 @@ export class StrictEnumField<
T extends object,
TRequireExplicitCache extends boolean,
> extends EnumField<TRequireExplicitCache> {
private readonly enum: T;
private readonly enumValues: ReadonlySet<string | number>;
constructor(
options: TRequireExplicitCache extends true
? EntityFieldDefinitionOptionsExplicitCache & { enum: T }
: EntityFieldDefinitionOptions & { enum: T },
) {
super(options);
this.enum = options.enum;
// Numeric TypeScript enums contain reverse mappings (e.g. { ADMIN: 0, 0: "ADMIN" });
// filter out the numeric string keys so reverse-mapped names don't pass validation.
this.enumValues = new Set(
Object.entries(options.enum)
.filter(([key]) => Number.isNaN(Number(key)))
Comment thread
wschurman marked this conversation as resolved.
.map(([, value]) => value)
.filter(
Comment thread
wschurman marked this conversation as resolved.
(value): value is string | number =>
typeof value === 'string' || typeof value === 'number',
),
);
}

protected override validateInputValueInternal(value: string | number): boolean {
return super.validateInputValueInternal(value) && Object.values(this.enum).includes(value);
return super.validateInputValueInternal(value) && this.enumValues.has(value);
}
}

Expand Down
11 changes: 11 additions & 0 deletions packages/entity/src/__tests__/EntityFields-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,23 @@ enum TestEnum {
WHO = 'wat',
}

enum NumericTestEnum {
ADMIN,
USER,
}

describeFieldTestCase(
new StrictEnumField({ columnName: 'wat', enum: TestEnum }),
[TestEnum.HELLO, TestEnum.WHO, 'world'],
['what', 1, true],
);

describeFieldTestCase(
new StrictEnumField({ columnName: 'wat', enum: NumericTestEnum }),
[NumericTestEnum.ADMIN, NumericTestEnum.USER],
['ADMIN', 'USER', 2, true],
);

describeFieldTestCase(
new BufferField({ columnName: 'wat' }),
[Buffer.from('hello')],
Expand Down