如何为MongoDB的collection.find()函数中找到的MongoDB排序属性实现GraphQL标量? [英] How to implement GraphQL Scalar for MongoDB sort property found in collection.find() function of MongoDB's?
问题描述
我正在尝试使用 type-graphql
创建一个参数类型,以通过GraphQL查询接受参数.我在说的 sort
是
I'm trying to create an argument type using type-graphql
to accept arguments through the GraphQL query. The sort
I'm talking about is a property of the options found on MongoDB's native NodeJS driver documentation.
@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;
}
如您所见,简单类型很好,但是当涉及到排序对象之类的东西时,我不确定该如何进行下去.
As you can see, simple types are fine, but when it comes to something like the sort object, I'm not sure how to go on about it.
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
替换什么?我要为 parseValue
, serialize
和 parseLiteral
输入什么?
Even in the example, it uses a returnTypeFunction @Scalar('Date', type => Date)
. What am I supposed to replace Date
with? What do I put in for parseValue
, serialize
, and parseLiteral
?
推荐答案
您可以只使用 @InputType
将对象嵌套在args中-您不需要标量,它们仅用于可序列化的内容,例如时间戳->数字,mongo id-> ObjectId实例等.
You can just use @InputType
to nest objects in args - you don't need scalars for that, they are designed only for serializable things like timestamp -> number, mongo id -> ObjectId instance, etc.
这篇关于如何为MongoDB的collection.find()函数中找到的MongoDB排序属性实现GraphQL标量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!