graphql的类型定义中的Date和Json

tab*_*bim 11 apollo graphql

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

type Individual {
    id: Int
    name: String
    birthDate: Date
    token: JSON
}
Run Code Online (Sandbox Code Playgroud)

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

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

和JSON一样的错误......

任何的想法 ?

And*_*rle 21

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

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

scalar Date

type MyType {
   created: Date
}
Run Code Online (Sandbox Code Playgroud)

并创建一个新的解析器:

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;
    },
  }),
Run Code Online (Sandbox Code Playgroud)


Mar*_*nte 8

原始的GraphQL标量类型IntFloatStringBooleanID。对于JSON并且Date您需要定义自己的自定义标量类型,文档非常清楚地说明了如何执行此操作。

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

scalar Date

type MyType {
   created: Date
}
Run Code Online (Sandbox Code Playgroud)

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

scalar Date

type MyType {
   created: Date
}
Run Code Online (Sandbox Code Playgroud)

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

import { GraphQLScalarType } from 'graphql';

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

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

对于JSON您可以使用graphql-type-json并导入它,如这里