【问题标题】:How do I use graphql-type-json scalar in Nest.js code first appraoch如何在 Next.js 代码优先方法中使用 graphql-type-json 标量
【发布时间】:2020-02-27 20:42:25
【问题描述】:

我已经 npm 安装了 graphql-type-json 和类型。 如何在代码优先的方法中使用它,其中 JSONObject 是下面示例中的标量。

import {Field, Int, InputType} from 'type-graphql';
import {Direction, MessageType} from '../interfaces/message.interface';

@InputType()
export class MessageInput {
    @Field()
    readonly to: string;

    @Field()
    readonly type: MessageType;

    @Field()
    readonly direction: Direction;

    @Field()
    readonly body: **JSONObject**;
}

【问题讨论】:

  • 感谢您提出这个问题。文档提出问题。

标签: graphql nestjs


【解决方案1】:

您可以使用the approach described in the docs 创建@Scalar() 类型

【讨论】:

  • 我不太明白 JSON 是怎么做的,你能举个例子吗?
  • 看起来已经有一个用于在 GraphQL 中输入 JSON 的包。 graphql-type-json。否则看起来你只需要添加一个 parseValue、一个序列化和一个 parseLiteral 方法。 Nest 文档展示了如何使用 Date 类型。
【解决方案2】:

我找到了这个方法,它对我有用。可能不是代码优先的方法,但我想在你弄清楚之前它就足够了:)

import { Field, ObjectType } from 'type-graphql';
import JSON from 'graphql-type-json';

@ObjectType()
export class YourClass {
  @Field(() => JSON)
  myProperty: any;
}

【讨论】:

    【解决方案3】:

    这不是很优雅,但我通过创建一个包装 GraphQLJSON 对象的 @Scalar 装饰类来做到这一点:

    // json.scalar.ts
    import { Scalar, CustomScalar } from '@nestjs/graphql';
    import * as GraphQLJSON from 'graphql-type-json';
    
    @Scalar('JSON', type => Object)
    export class JsonScalar implements CustomScalar<string, any> {
      name = GraphQLJSON.name;
      description = GraphQLJSON.description;
    
      serialize = GraphQLJSON.serialize;
      parseValue = GraphQLJSON.parseValue;
      parseLiteral = GraphQLJSON.parseLiteral;
    }
    

    然后我只是将JsonScalar 添加到模块中的resolvers 部分。

    您可以在带有@Query(returns =&gt; Object) 的解析器中使用它,其他需要指定嵌套类型的地方也是如此,它只是Object

    Nestjs 应该真的允许我们按对象而不是按类添加标量,很惊讶这不是一回事。我从模式优先切换到代码优先并遇到了这个问题。

    【讨论】:

    • 聪明地使用Object。感谢分享。
    猜你喜欢
    • 2021-10-30
    • 2020-08-17
    • 2020-07-14
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多