在 NestJS 中检查查询参数的干净方法

发布于 2025-01-17 03:53:05 字数 537 浏览 5 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

离不开的别离 2025-01-24 03:53:05

正如 Micael Levi 所提到的,您应该能够通过创建自己的自定义管道来做到这一点。假设您发布的内容有效,您应该能够执行以下操作:

@Get('/some-resources')
async getSomeResource(
  @Query('startDate', ParseDateIsoPipe) startDate?: string, 
  @Query('endDate', ParseDateIsoPipe) endDate?: string
): Promise<HTTPResponseDTO>{
 <code>
}

使用 ParseDateIsoPipe 如下(请注意,您仍然需要从正在使用的包中导入 DateTime):

import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class ParseDateIsoPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    return value ? DateTime.fromISO(value).startOf('day').toISO(): null;
  }
}

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:

@Get('/some-resources')
async getSomeResource(
  @Query('startDate', ParseDateIsoPipe) startDate?: string, 
  @Query('endDate', ParseDateIsoPipe) endDate?: string
): Promise<HTTPResponseDTO>{
 <code>
}

With your ParseDateIsoPipe as follows (Note that you will still need to import DateTime from the package you are using):

import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class ParseDateIsoPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    return value ? DateTime.fromISO(value).startOf('day').toISO(): null;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文