Skip to content

Commit

Permalink
fix: enum name extraction after typescript build
Browse files Browse the repository at this point in the history
  • Loading branch information
mdovhopo committed Jan 20, 2022
1 parent 322b989 commit 8585747
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
6 changes: 0 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions src/decorators/is-enum.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,25 @@ describe('IsEnum', () => {
enumField!: Enum;
}

it('works with enums after TypeScript build', async () => {
// Emulate Enum name after TS build - module_1.TestEnum
const module_1 = {
Enum
}

class TestDto {
@IsEnum({ enum: () => module_1.Enum })
enumField!: Enum;
}

expect(await input(TestDto, { enumField: 'On' })).toStrictEqual(
Result.ok(make(TestDto, { enumField: Enum.On }))
);
expect(await input(TestDto, { enumField: 'Off' })).toStrictEqual(
Result.ok(make(TestDto, { enumField: Enum.Off }))
);
})

it('generates correct schema', async () => {
expect(await generateSchemas([Test])).toStrictEqual({
Enum: {
Expand Down
13 changes: 9 additions & 4 deletions src/decorators/is-enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,16 @@ function getEnumNameAndValues<T extends number | string>(
}

function getEnumNameFromFunction(e: () => unknown) {
const enumName = e.toString().split('=>')[1].trim();
const fullEnumName = e.toString().split('=>')[1].trim();

if (!/^\w+$/.test(enumName)) {
throw new Error(`Invalid enum name: ${enumName}`);
// after TS build to commonjs modules enums are
// replaced with {module-name}.{enum}, example gender_1.Gender
// So need to extract actuall enumName
const match = fullEnumName.match(/^(\w+\.)?(?<name>\w+)$/);

if (!match) {
throw new Error(`Invalid enum name: ${fullEnumName}`);
}

return enumName;
return match.groups?.name;
}

0 comments on commit 8585747

Please sign in to comment.