graphql的类型定义中的Date和Json

时间:2018-04-06 13:27:34

标签: graphql apollo

是否可以在我的graphql架构中将字段定义为Date或JSON?

type Individual {
    id: Int
    name: String
    birthDate: Date
    token: JSON
}

实际上服务器正在给我一个错误说:

Type "Date" not found in document.
at ASTDefinitionBuilder._resolveType (****node_modules\graphql\utilities\buildASTSchema.js:134:11)

JSON的错误......

有什么想法吗?

2 个答案:

答案 0 :(得分:14)

查看自定义标量:https://www.apollographql.com/docs/graphql-tools/scalars.html

在架构中创建一个新标量:

scalar Date

type MyType {
   created: Date
}

并创建一个新的解析器:

import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';

const resolverMap = {
  Date: new GraphQLScalarType({
    name: 'Date',
    description: 'Date custom scalar type',
    parseValue(value) {
      return new Date(value); // value from the client
    },
    serialize(value) {
      return value.getTime(); // value sent to the client
    },
    parseLiteral(ast) {
      if (ast.kind === Kind.INT) {
        return parseInt(ast.value, 10); // ast value is always in string format
      }
      return null;
    },
  }),

答案 1 :(得分:2)

原始 scalar types in GraphQLIntFloatStringBooleanID。对于 JSONDate,您需要定义自己的自定义标量类型,the documentation 非常清楚如何执行此操作。

在您的架构中,您必须添加:

scalar Date

type MyType {
   created: Date
}

然后,在您的代码中,您必须添加类型实现:

import { GraphQLScalarType } from 'graphql';

const dateScalar = new GraphQLScalarType({
  name: 'Date',
  parseValue(value) {
    return new Date(value);
  },
  serialize(value) {
    return value.toISOString();
  },
})

最后,您必须在解析器中包含此自定义标量类型:

const server = new ApolloServer({
  typeDefs,
  {
    Date: dateScalar,
    // Remaining resolvers..
  },
});

Date 实现将解析 Date constructor 接受的任何字符串,并将日期作为 ISO 格式的字符串返回。

对于 JSON,您可以使用 graphql-type-json 并将其导入,如 here 所示。