如何为在 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
是在 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;
}
如您所见,简单类型很好,但是当涉及到诸如排序对象之类的东西时,我不确定如何进行下去。
NestJS implements a date scalar like so:
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
输入什么?
您可以只使用 @InputType
在 args 中嵌套对象 - 您不需要标量,它们仅设计用于可序列化的东西,如时间戳 -> 数字,mongo id -> ObjectId实例等
我正在尝试使用 type-graphql
创建参数类型以通过 GraphQL 查询接受参数。我说的 sort
是在 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;
}
如您所见,简单类型很好,但是当涉及到诸如排序对象之类的东西时,我不确定如何进行下去。
NestJS implements a date scalar like so:
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
输入什么?
您可以只使用 @InputType
在 args 中嵌套对象 - 您不需要标量,它们仅设计用于可序列化的东西,如时间戳 -> 数字,mongo id -> ObjectId实例等