【发布时间】:2020-01-04 22:11:58
【问题描述】:
我正在使用 GrapQL、Node 和 PostgreSQL 开发一个待办事项列表应用程序。
作为我的实体,我有一张卡片,其中包含 DateTime 的这些字段: created_at 和 updated_at。
我设法创建一个标量 Date 来管理 DateTime 格式,但时间采用以下格式:
"created_at": "2019-08-24T23:11:02.376Z",
"updated_at": "2019-09-01T15:04:12.627Z"
我想要显示我所在时区的实际时间的格式。上面的时间是Z,比我的时间晚了2小时。
我的标量日期如下:
import { GraphQLScalarType, GraphQLError } from 'graphql';
import { Kind } from 'graphql/language';
import { isISO8601 } from 'validator';
export default new GraphQLScalarType({
name: 'Date',
description: 'Date type',
parseValue(value): Date {
if (isISO8601(value))
// value comes from the client
return new Date(value); // sent to resolvers
throw new Error('DateTime cannot represent an invalid ISO-8601 Date string');
},
serialize(value): Promise<string> {
if (isISO8601(value))
// value comes from resolvers
return value.toISOString(); // sent to the client
throw new Error('DateTime cannot represent an invalid ISO-8601 Date string');
},
parseLiteral(ast): Date {
// ast comes from parsing the query
// this is where you can validate and transform
if (ast.kind !== Kind.STRING) {
throw new GraphQLError(`Query error: Can only parse dates strings, got a: ${ast.kind}`, [ast]);
}
if (isNaN(Date.parse(ast.value))) {
throw new GraphQLError(`Query error: not a valid date`, [ast]);
}
if (isISO8601(ast.value)) return new Date(ast.value);
throw new Error('DateTime cannot represent an invalid ISO-8601 Date string');
},
});
我的卡片实体:
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
@Entity('cards')
export class Card {
@PrimaryGeneratedColumn('uuid')
id: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@Column('text')
title: string;
@Column('text', {
nullable: true,
})
description: string;
@Column('boolean', {
default: 'false',
})
done: boolean;
}
卡片类型:
export const Card = `
scalar Date
type Card {
id : String
title : String
description : String
done : Boolean
created_at : Date
updated_at : Date
}
`;
【问题讨论】:
标签: node.js postgresql graphql