[英]How to define a Date Scalar using GraphQL-JS?
我正在尝试在 GraphQL 中定义一个自定义标量,以便我可以查询和处理我的 MongoDB 集合中的日期。 我不确定我是否 100% 理解标量是什么或做什么,但它似乎是我自己定义的一种类型。 我发现的所有示例和教程都使用 Apollo 或其他类型的符号,但我希望看到使用GraphQL-JS的解决方案
到目前为止,我已经像这样定义了我的标量:
const Date = new GraphQLScalarType({
name: "Date",
serialize: (value) => {
return value; //is it correct, to just return the value? Do I need to parse it or turn it into a Date first?
},
parseValue: () => {
return "serialise"; //I am just returning this string here, because I do not know what this function is for
},
parseLiteral(ast) {
return null; //I am just returning null here, because I do not know what this function is for
},
});
我不确定我是否理解这些功能中的每一个应该做什么。 不是也必须有deserialize
功能吗?
当我现在查询我的 graphql 端点时,我确实得到了类似的信息:
{
"myDate": "2020-07-15T00:00:00.000Z"
}
我猜我的serialise
功能在这里起作用了? 日期当然是正确的,但我不确定在从serialize
返回数据之前是否应该对数据做任何其他事情? 现在我只返回我从我的 MongoDB 数据库中得到的任何东西。
来自 The Guild 的graphql-scalars
创建了graphql-scalars
,其中包含 GraphQL 中使用的多个常见标量的定义
//是否正确,只返回值? 我是否需要先解析它或将其转换为日期?
在返回它之前验证该value
是一个Date
是明智的。 是的,只需返回值。
//我这里只是返回null,因为我不知道这个函数是干什么用的
这是来自抽象语法树 (ast) 的条目。 请参阅下面的Urigo
代码以了解如何访问ast
对象
ast.kind
ast.value
另外,看看这个 SO post,它描述了parseValue
和parseLiteral
之间的区别
看看localDate
,它可能为您提供回答问题所需的示例:)
export const GraphQLLocalDate = /*#__PURE__*/ new GraphQLScalarType({
name: 'LocalDate',
description:
'A local date string (i.e., with no associated timezone) in `YYYY-MM-DD` format, e.g. `2020-01-01`.',
serialize(value) {
// value sent to client as string
return validateLocalDate(value);
},
parseValue(value) {
// value from client as json
return validateLocalDate(value);
},
parseLiteral(ast) {
// value from client in ast
if (ast.kind !== Kind.STRING) {
throw new GraphQLError(
`Can only validate strings as local dates but got a: ${ast.kind}`,
);
}
return validateLocalDate(ast.value);
},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.