如何实现 MongoDB 的 GraphQL Scalar 排序属性,该属性在 MongoDB 的 collection.find() 函数中找到?



我正试图使用type-graphql创建一个参数类型,以通过GraphQL查询接受参数。我所说的sort是MongoDB原生NodeJS驱动程序文档中选项的一个属性。

@ArgsType()
export class FindAllArgs implements FindOneOptions {
@Field(type => Int, { defaultValue: 0, description: 'Sets the limit of documents returned in the query.' })
@Min(0)
limit?: number;
// This is where the custom sort would go about.
@Field(type => SortScalar)
sort?: sortScalar;
@Field(type => Int, { defaultValue: 0, description: 'Set to skip N documents ahead in your query (useful for pagination).' })
@Min(0)
skip?: number;
}

正如你所看到的,简单的类型是可以的,但当涉及到像排序对象这样的东西时,我不知道该如何处理

NestJS实现了一个类似这样的日期标量:

import { Scalar, CustomScalar } from '@nestjs/graphql';
import { Kind, ValueNode } from 'graphql';
@Scalar('Date', type => Date)
export class DateScalar implements CustomScalar<number, Date> {
description = 'Date custom scalar type';
parseValue(value: number): Date {
return new Date(value); // value from the client
}
serialize(value: Date): number {
return value.getTime(); // value sent to the client
}
parseLiteral(ast: ValueNode): Date {
if (ast.kind === Kind.INT) {
return new Date(ast.value);
}
return null;
}
}

即使在示例中,它也使用returnTypeFunction@Scalar('Date', type => Date)。我应该用什么来替换Date?我为parseValueserializeparseLiteral输入了什么?

您可以使用@InputType在args中嵌套对象-您不需要标量,它们只用于可序列化的东西,如时间戳->数字、mongo id->ObjectId实例等。

最新更新