【问题标题】:graphql 类型定义中的日期和 Json
【发布时间】:2018-09-16 13:10:41
【问题描述】:

是否可以在我的 graphql 架构中将字段定义为日期或 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 也有同样的错误...

有什么想法吗?

【问题讨论】:

  • 虽然这个线程中给出的解决方案是开胃和完整的。我已经看到,当您使用github.com/Soluto/graphql-to-mongodb 之类的适配器时,我们无法创建自己的类型,因此在这种情况下,我直接将日期作为时间存储在数据库中,并使用浮点类型。 js 有 (new Date()).getTime() 来协助和使用解析器将其转换为所需的日期格式作为字符串在任何需要的地方 - new Date(1324339200000); date.toString("MMM dd");

标签: graphql apollo


【解决方案1】:

原始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 所示。

【讨论】:

    【解决方案2】:

    查看自定义标量: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;
        },
      }),
    

    【讨论】:

    • 该示例中的查询如何? 10.02.1993??
    • 只是想提一下,这个 sn-p 仅在您传递的日期是数字时才有效。例如,“2020-01-01”虽然是有效日期,但不会被解析,因为它只需要一个数字。
    猜你喜欢
    • 2018-10-19
    • 2020-06-01
    • 2021-03-17
    • 2021-11-20
    • 2020-05-05
    • 2018-06-06
    • 2017-08-16
    • 2019-12-15
    • 2021-03-04
    相关资源
    最近更新 更多