GraphQL.js - 时间戳标量类型?

6

我正在以编程方式构建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时间戳类型呢?

1个回答

5

有一个符合RFC 3339标准的日期/时间GraphQL标量类型的NPM包;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来源于他的)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接