graphql的类型定义中的Date和Json [英] Date and Json in type definition for graphql

查看:844
本文介绍了graphql的类型定义中的Date和Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to have a define a field as Date or JSON in my graphql schema ?

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

实际上服务器正在向我返回一条错误消息:

actually the server is returning me an error saying :

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

同样的JSON错误...

And same error for JSON...

有什么主意吗?

推荐答案

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

在您的模式中创建一个新的标量:

create a new scalar in your schema:

scalar Date

type MyType {
   created: Date
}

并创建一个新的解析器:

and create a new resolver:

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;
    },
  }),

这篇关于graphql的类型定义中的Date和Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆