【发布时间】:2021-09-25 12:26:49
【问题描述】:
我正在尝试在 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 数据库中获得的任何内容。
【问题讨论】:
-
谢谢,这解释了这两个函数之间的区别。但是,我的问题更广泛,涉及 GraphQL-JS 中的标量 - 我在这里找不到任何相关内容,所以我真的不明白反对意见。
-
不是一个学习平台...你可以找到解释/教程...moonhighway.com/creating-custom-scalars
标签: javascript node.js mongodb graphql graphql-js