在 NestJS 中检查查询参数的干净方法
我有一个 Nestjs 项目,主要采用 RESTful 结构。一切工作正常,但我担心的是某些路由检查是否存在某些查询参数来获取数据。 例如
@Get('/some-resources')
async getSomeResource(
@Query() query: any
): Promise<HTTPResponseDTO>{
const startDate = query.startDate ? DateTime.fromISO(query.startDate).startOf('day').toISO(): null;
const endDate = query.endDate ? DateTime.fromISO(query.endDate).endOf('day').toISO() : null;
.
.
.
const result = await this.someResourceService.findAll(startDate, endDate,...)
}
,现在我的问题是,是否有更干净的方法?因为当我们拥有很多资源时,维护起来会变得很痛苦。
I have a nestjs project that is mostly in RESTful structure. Everything works fine, but my concern is that some of the routes check for the presence of some query parameters to fetch data.
for instance
@Get('/some-resources')
async getSomeResource(
@Query() query: any
): Promise<HTTPResponseDTO>{
const startDate = query.startDate ? DateTime.fromISO(query.startDate).startOf('day').toISO(): null;
const endDate = query.endDate ? DateTime.fromISO(query.endDate).endOf('day').toISO() : null;
.
.
.
const result = await this.someResourceService.findAll(startDate, endDate,...)
}
Now my question is, is there a cleaner approach to this? Because this can get become a pain to maintain when we have many resources.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Micael Levi 所提到的,您应该能够通过创建自己的自定义管道来做到这一点。假设您发布的内容有效,您应该能够执行以下操作:
使用 ParseDateIsoPipe 如下(请注意,您仍然需要从正在使用的包中导入 DateTime):
As mentioned by Micael Levi, you should be able to do this by creating your own custom pipe. Assuming that what you posted works, you should be able to do something along the lines of:
With your ParseDateIsoPipe as follows (Note that you will still need to import DateTime from the package you are using):
您可以使用内置验证管道: https://docs.nestjs.com/techniques/validation< /a> 具有自动验证功能。
You can use the built-in validation pipe: https://docs.nestjs.com/techniques/validation with the auto validation feature.