GraphQL 的类型:
- Int 整形 (GraphQLInt)
- Float 浮点型 (GraphQLFloat)
- String 字符串类型
- Boolean 布尔类型
- ID 唯一类型 (GraphQLID)
- 自定义类型: Date (GraphQLISODateTime 日期/GraphQLTimestamp 时间戳)
自定义标量 Date
- 分为定义标量
- 使用标量
首先自定义标量要实现 CustomScalar 类, 这个类来源于 @nestjs/graphql 包,我们需要下载这个包。同时我们还需要 Kind, ValueNode,用于解析,而解析任务是在 graphql.js 中完成的。
自定义标量都要实现一个属性和三个方法:
- description 属性
- parseValue 解析 date, 从客户端获取
- serialize 序列化date, 将数据发送到客户端
- parseLiteral 解析字面量
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;
}
}
使用字面量:
我们要通过模块的方式,将 DateScalar 标量添加到 nestjs graphql 中使用。
@Module({
providers: [DateScalar],
})
export class CommonModule {}
// 表示字段是 Date 标量类型
@Field()
creationDate: Date;