How to implement GraphQL Scalar for MongoDB sort property found in collection.find() function of MongoDB's?

强颜欢笑 提交于 2021-01-29 13:40:13

问题


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 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;
  }
}

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?


回答1:


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.



来源:https://stackoverflow.com/questions/58976826/how-to-implement-graphql-scalar-for-mongodb-sort-property-found-in-collection-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!