Reputation: 38485
I'm making an api which looks like:
http://example.com/story/:storyId/analytics?from={date}&to={date}
The storyId
is part of the path, but from
and to
are query parameters.
I've got a DTO, like this:
class GetStoryAnalyticsDTO {
storyId: string
from: Date
to: Date
}
(validators omitted for brevity)
And I'm using it like this in my controler:
@Get()
getStoryAnalytics(@Query() query: GetStoryAnalyticsRequestDto): Promise<MyResponse> {...}
But, (obviously!), this only extracts the from and to parameters.
Is there any way to extract both from the query and the path to get all the vars in one dto?
If not, it's not a massive hassle - I can just add @Param storyId: string
to the controller and it's all good :)
Upvotes: 1
Views: 2016
Reputation: 70570
You could make a custom decorator like @QueryParam()
that pulls together req.query
and req.params
. It could look something like this:
export const QueryParam = createParamDecorator((data: unknown, context: ExecutionContext) => {
const req = context.switchToHttp().getRequest();
return { ...req.query, ...req.params };
});
And just make sure to add validateCustomDecorators
on the ValidationPipe
if you want it to auto validate for you. Otherwise, you're good to start using it.
Upvotes: 3