我有NestJS应用程序,我必须从URL获取查询。问题是,我的creationDate是一个对象,我不能得到它作为嵌套对象通过@Query。
下面是路由的例子:
xxx/yyy/orders?key1=value&key2=value&key3=value&createdAt[lte]=2021-07-01&createdAt[gte]=2011-03-30&orderBy=desc&limit=500
我正在尝试获得createdAt[lte]和createdAt[gte]作为嵌套对象
export interface QueryI {
key1: string;
key2: string;
key3: string;
key4: string;
createdAt: {
lte: string,
gte: string,
}
orderBy: 'desc' | 'asc';
limit: number;
}
这是我的控制器:
@Get('route')
getAll(
@Query() query: QueryI): Promise<void> {
return this.myService.findAll(query);
}
但这给了我以下结果
{
key1: 'value',
key2: 'value',
key3: 'value',
key4: 'value',
'createdAt[lte]': 'some date',
'createdAt[gte]': 'some date',
orderBy: 'desc',
limit: '500'
}
我试过JSON。stringify在SOW上咨询了类似的问题,但没有运气。
谢谢
EDIT
最后我实现了不同的类,并使用@Pipe来验证我的查询:
pipe.ts
@Injectable()
export class ValidateQueryPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
let incomingQuery = value as IncomingQuery;
let mappedQuery = new QueryParameters()
mappedQuery.key1 = incomingQuery.key1
mappedQuery.key2= incomingQuery.key2
// other mapped valus
mappedQuery.createdAt = new CreatedAt(incomingQuery['createdAt[lte]'], incomingQuery['createdAt[gte]'])
return mappedQuery;
}
controller.ts
@Get(':someurl/someurl')
getAllOrders(
@Query(ValidateQueryPipe) query: QueryParameters): Promise<Observable<any>> {
return this.service.findAll(erpCode, query);
}
query-parameters.ts
import { CreatedAt } from "./created-at";
export class QueryParameters {
key1: string;
key2: string;
createdAt: CreatedAt;
}
created-at.ts
export class CreatedAt {
lte: string;
gte: string;
constructor(lte: string, gte: string){
this.lte = lte;
this.gte = gte;
};
}
我已经找到了一个部分的解决方案,我会把它贴在这里,直到更好的答案出现:我正在将嵌套属性提取到单独的查询中并创建我的模型。它不是完美的,但它现在做的工作…
controller.ts
getAllOrders(
@Query() query,
@Query('createdAt[lte]') lte: string,
@Query('createdAt[gte]') gte: string): Promise<void> {
const mappedObject = new QueryParameters(query, lte, gte)
return this.orderService.findAll(erpCode, mappedObject);
}
createdAtModel.ts
export class CreatedAt {
lte: string;
gte: string;
constructor(lte: string, gte: string){
this.lte = lte;
this.gte = gte;
};
}
my-model.ts
import { CreatedAt } from "./created-at";
export class QueryParameters {
//other keys
createdAt: CreatedAt;
constructor(query, lte, gte){
//other keys
this.createdAt = new CreatedAt(lte, gte)
}
}
我确信更好的答案在于使用NestJS验证管道,但我没有设法找到一个适合我的。
将QueryI
从接口切换到类。
正在开发NestJS 7.
用于测试的Url
http://localhost:3000/api/v1/store/search?nestedObj[key1]=yolo&nestedObj[key2]=sup%20bruh&el=test
DTO使用
export class TestDto {
el: string;
nestedObj: {
key1: string;
key2: string;
};
}
控制器
@Controller('v1/store')
@UsePipes(new ValidationPipe({ exceptionFactory: getFormattedErrors }))
@UseFilters(DomainExceptionFilter)
export class TestController{
@Get('search')
public async searchStore(@Query() testDto: TestDto) {
console.log(testDto);
return 1;
}
}
// Console log - { nestedObj: { key1: 'yolo', key2: 'sup bruh' }, el: 'test' }