Skip to content

Commit

Permalink
refactor: improve ApiParam decorator to use shared addEnumSchema
Browse files Browse the repository at this point in the history
  • Loading branch information
lucas-gregoire committed Nov 30, 2023
1 parent e373243 commit 508a559
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 17 deletions.
4 changes: 2 additions & 2 deletions e2e/api-spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -837,12 +837,12 @@
"required": true,
"in": "path",
"schema": {
"type": "string",
"enum": [
"A",
"B",
"C"
]
],
"type": "string"
}
},
{
Expand Down
18 changes: 4 additions & 14 deletions lib/decorators/api-param.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
SchemaObject
} from '../interfaces/open-api-spec.interface';
import { SwaggerEnumType } from '../types/swagger-enum.type';
import { getEnumType, getEnumValues } from '../utils/enum.utils';
import { addEnumSchema, getEnumType, getEnumValues, isEnumDefined } from '../utils/enum.utils';
import { createParamDecorator } from './helpers';

type ParameterOptions = Omit<ParameterObject, 'in' | 'schema'>;
Expand All @@ -29,24 +29,14 @@ const defaultParamOptions: ApiParamOptions = {
};

export function ApiParam(options: ApiParamOptions): MethodDecorator {
const param: Record<string, any> = {
const param: ApiParamMetadata & Record<string, any> = {
name: isNil(options.name) ? defaultParamOptions.name : options.name,
in: 'path',
...omit(options, 'enum')
};

const apiParamMetadata = options as ApiParamMetadata;
if (apiParamMetadata.enum) {
param.schema = param.schema || ({} as SchemaObject);

const paramSchema = param.schema as SchemaObject;
const enumValues = getEnumValues(apiParamMetadata.enum);
paramSchema.type = getEnumType(enumValues);
paramSchema.enum = enumValues;

if (apiParamMetadata.enumName) {
param.enumName = apiParamMetadata.enumName;
}
if (isEnumDefined(options)) {
addEnumSchema(param, options);
}

return createParamDecorator(param, defaultParamOptions);
Expand Down
2 changes: 1 addition & 1 deletion lib/utils/enum.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ export function addEnumSchema(
const enumValues = getEnumValues(decoratorOptions.enum);

paramDefinition.schema = paramSchema;
paramSchema.enum = enumValues;
paramSchema.type = getEnumType(enumValues);
paramSchema.enum = enumValues;

if (decoratorOptions.enumName) {
paramDefinition.enumName = decoratorOptions.enumName;
Expand Down

0 comments on commit 508a559

Please sign in to comment.