Reputation: 5695
Currently, I am using DTO objects in my controllers and I am pairing them with the class-validator plugin as to parse/validate them. The thing is, I want to assign default values to some of the DTO parameters, but those values should come from configuration. I need some elegant way to inject those default values into the DTO and also get those default values automatically populated in the swagger metainformation for the respective endpoints(I am using the nest swagger plugin to automatically apply the decorators for me). In order to achieve the desired result I see 2 solutions both of which require some unwanted compromises.
Solution 1: Inject the configuration values into the controller itself and after parsing the DTO in the route handler, passing the parameters and the DTO to a method which will apply them over the DTO. In order to document the default values in the swagger, however, I should manually put '@ApiQuery' attributes over the handler for the default values. First, in this case I use both DTO and also query decorators for the swagger specifically and also I am not sure if that will even work. In short, it is a total mess and I prefer to avoid this 'solution'.
Solution 2: Entirely skip the DTO approach and go with separate query parameters. I can apply the default values with the default pipe by injecting the configuration into the controller. However, I need to apply the validation rules for each parameter or creating a DTO anyway on which I can apply the validation rules and construct it manually from the query params. Also, I need to manually document all the parameters for swagger to pick-up.
Any better solutions?
Upvotes: 2
Views: 5213
Reputation: 446
You can directly pass default value in ApiProperty decorator like this in your Dto...
@ApiProperty({ default: 'https://www.youtube.com/watch?v=CjG8u6ZZpag' })
@IsString()
@IsNotEmpty()
readonly keyName: string;
Upvotes: 4
Reputation: 2987
You can pass default values from an interceptor and import your default data from your configuration files.
Upvotes: 1