是否可以在我的graphql架构中将字段定义为Date或JSON?
type Individual {
id: Int
name: String
birthDate: Date
token: JSON
}
实际上服务器正在给我一个错误说:
Type "Date" not found in document.
at ASTDefinitionBuilder._resolveType (****node_modules\graphql\utilities\buildASTSchema.js:134:11)
JSON的错误......
有什么想法吗?
答案 0 :(得分:14)
查看自定义标量:https://www.apollographql.com/docs/graphql-tools/scalars.html
在架构中创建一个新标量:
scalar Date
type MyType {
created: Date
}
并创建一个新的解析器:
import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';
const resolverMap = {
Date: new GraphQLScalarType({
name: 'Date',
description: 'Date custom scalar type',
parseValue(value) {
return new Date(value); // value from the client
},
serialize(value) {
return value.getTime(); // value sent to the client
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return parseInt(ast.value, 10); // ast value is always in string format
}
return null;
},
}),
答案 1 :(得分:2)
原始 scalar types in GraphQL 是 Int
、Float
、String
、Boolean
和 ID
。对于 JSON
和 Date
,您需要定义自己的自定义标量类型,the documentation 非常清楚如何执行此操作。
在您的架构中,您必须添加:
scalar Date
type MyType {
created: Date
}
然后,在您的代码中,您必须添加类型实现:
import { GraphQLScalarType } from 'graphql';
const dateScalar = new GraphQLScalarType({
name: 'Date',
parseValue(value) {
return new Date(value);
},
serialize(value) {
return value.toISOString();
},
})
最后,您必须在解析器中包含此自定义标量类型:
const server = new ApolloServer({
typeDefs,
{
Date: dateScalar,
// Remaining resolvers..
},
});
此 Date
实现将解析 Date
constructor 接受的任何字符串,并将日期作为 ISO 格式的字符串返回。
对于 JSON
,您可以使用 graphql-type-json
并将其导入,如 here 所示。