Skip to content

Commit

Permalink
Merge pull request #1898 from petrzjunior/master
Browse files Browse the repository at this point in the history
fix: fix numeric enum values
  • Loading branch information
kamilmysliwiec committed Feb 6, 2023
2 parents 21dcb69 + d4d6f8c commit df7cf9b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 22 deletions.
35 changes: 20 additions & 15 deletions lib/utils/enum.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,27 @@ export function getEnumValues(enumType: SwaggerEnumType): string[] | number[] {
if (typeof enumType !== 'object') {
return [];
}
/*
Enums with numeric values
enum Size {
SMALL = 1,
BIG = 2
}
are transpiled to include a reverse mapping
const Size = {
"1": "SMALL",
"2": "BIG",
"SMALL": 1,
"BIG": 2,
}
*/
const numericValues = Object.values(enumType)
.filter((value) => typeof value === 'number')
.map((value) => value.toString());

const values = [];
const uniqueValues = {};

for (const key in enumType) {
const value = enumType[key];
// filter out cases where enum key also becomes its value (A: B, B: A)
if (
!uniqueValues.hasOwnProperty(value) &&
!uniqueValues.hasOwnProperty(key)
) {
values.push(value);
uniqueValues[value] = value;
}
}
return values;
return Object.keys(enumType)
.filter((key) => !numericValues.includes(key))
.map((key) => enumType[key]);
}

export function getEnumType(values: (string | number)[]): 'string' | 'number' {
Expand Down
14 changes: 7 additions & 7 deletions test/explorer/swagger-explorer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -860,9 +860,9 @@ describe('SwaggerExplorer', () => {
}

enum QueryEnum {
D = 'd',
E = 'e',
F = 'f'
D = 1,
E,
F = (() => 3)()
}

class Foo {}
Expand Down Expand Up @@ -965,8 +965,8 @@ describe('SwaggerExplorer', () => {
name: 'order',
required: true,
schema: {
type: 'string',
enum: ['d', 'e', 'f']
type: 'number',
enum: [1, 2, 3]
}
},
{
Expand Down Expand Up @@ -1007,8 +1007,8 @@ describe('SwaggerExplorer', () => {
name: 'order',
required: true,
schema: {
type: 'string',
enum: ['d', 'e', 'f']
type: 'number',
enum: [1, 2, 3]
}
},
{
Expand Down

0 comments on commit df7cf9b

Please sign in to comment.