I am dealing with a query parameter in my REST API that should be restricted to specific values according to an enum type. I need to find a way to handle a "Bad Request" error if the client provides any value outside of this enum.
Here is what my enum looks like:
export enum Precision {
S = 's',
MS = 'ms',
U = 'u',
NS = 'ns',
}
This is how my controller function is structured:
@Get(':deviceId/:datapoint/last')
@ApiOkResponse()
@ApiQuery({name: 'precision', enum: Precision})
getLastMeasurement(
@Param('deviceId') deviceId: string,
@Param('datapoint') datapoint: string,
@Query('precision') precision: Precision = Precision.S,
@Res() response: Response,
) {
console.log(precision);
....
response.status(HttpStatus.OK).send(body);
}
The issue I am facing is that the function currently allows for other values besides those defined in the enum (e.g., accepting 'f' as a query parameter value). While no error is returned to the client, I want to address this without having to include an if-else block at the beginning of each controller function.
I believe there must be a straightforward solution to enforcing enum validation directly in the query parameter and REST controller, but my searches online have mainly yielded results related to class validation in DTOs rather than this specific scenario.
Thank you for your time,
J