【问题标题】:How to define a Date Scalar using GraphQL-JS?如何使用 GraphQL-JS 定义日期标量?
【发布时间】: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 数据库中获得的任何内容。

【问题讨论】:

标签: javascript node.js mongodb graphql graphql-js


【解决方案1】:

来自 The Guild 的 Urigo 创建了 graphql-scalars,其中包含 GraphQL 中使用的多个常见标量的定义

//是否正确,只返回值?我需要先解析它还是把它变成一个日期?

在返回之前验证valueDate 是明智的。 是的,只需返回值。

//我这里只是返回null,因为我不知道这个函数是干什么用的

这是来自抽象语法树 (ast) 的条目。 请参阅下面Urigo 的代码以了解如何访问ast 对象

  • ast.kind
  • ast.value

Additionally, take a look at this SO post that describes the difference between parseValue and 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);
  },
});

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2017-05-24
    • 2022-08-05
    • 2018-05-29
    • 2020-08-03
    • 2020-10-01
    • 2020-10-21
    • 2018-12-04
    • 2018-02-12
    相关资源
    最近更新 更多