代码之家  ›  专栏  ›  技术社区  ›  Mohamed Taboubi

graphql类型定义中的日期和Json

  •  55
  • Mohamed Taboubi  · 技术社区  · 8 年前

    在我的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 回复  |  直到 8 年前
        1
  •  71
  •   Andreas Köberle    8 年前

    查看自定义标量: 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;
        },
      }),
    
        2
  •  14
  •   iamkirill Martín De la Fuente    4 年前

    原始的 scalar types in GraphQL Int ,则, Float ,则, String ,则, Boolean ID 对于 JSON Date 您需要定义自己的自定义标量类型, 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,
      resolvers: {
        Date: dateScalar,
        // Remaining resolvers..
      },
    });
    

    日期 实现将解析 Date constructor ,并将以ISO格式的字符串形式返回日期。

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