【问题标题】:GraphQL.js - timestamp scalar type?GraphQL.js - 时间戳标量类型?
【发布时间】:2019-01-20 16:24:02
【问题描述】:

我正在以编程方式构建一个 GraphQL 模式,并且需要一个 Timestamp 标量类型; Unix Epoch timestamp 标量类型:

const TimelineType = new GraphQLObjectType({
  name: 'TimelineType',
  fields: () => ({
    date:  { type: new GraphQLNonNull(GraphQLTimestamp)  },
    price: { type: new GraphQLNonNull(GraphQLFloat)      },
    sold:  { type: new GraphQLNonNull(GraphQLInt)        }
  })
});

不幸的是,GraphQL.js 没有GraphQLTimestampGraphQLDate 类型,所以上面的方法不起作用。

我期待Date 输入,我想将其转换为时间戳。我将如何创建自己的 GraphQL 时间戳类型?

【问题讨论】:

    标签: javascript schema graphql graphql-js scalar


    【解决方案1】:

    有一个 NPM 包,其中包含一组符合 RFC 3339 的日期/时间 GraphQL 标量类型; graphql-iso-date.


    但对于初学者,您应该使用GraphQLScalarType 以编程方式在 GraphQL 中构建自己的标量类型:

    /** Kind is an enum that describes the different kinds of AST nodes. */
    import { Kind } from 'graphql/language';
    import { GraphQLScalarType } from 'graphql';
    
    const TimestampType = new GraphQLScalarType({
      name: 'Timestamp',
      serialize(date) {
        return (date instanceof Date) ? date.getTime() : null
      },
      parseValue(date) {
        try           { return new Date(value); }
        catch (error) { return null; }
      },
      parseLiteral(ast) {
        if (ast.kind === Kind.INT) {
          return new Date(parseInt(ast.value, 10));
        }
        else if (ast.kind === Kind.STRING) {
          return this.parseValue(ast.value);
        }
        else {
          return null;
        }
      },
    });
    

    但不是重新发明轮子,而是已经讨论了这个问题 (#550),Pavel Lang 提出了一个不错的GraphQLTimestamp.js 解决方案(我的TimestampType 来自他的)。

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 2021-08-26
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 2018-06-24
      • 2012-02-17
      • 1970-01-01
      相关资源
      最近更新 更多