【问题标题】:NestJS: Can we use custom Type and Classes when defining InputType and ObjectType Field with GraphQL & MongoDBNestJS:我们可以在使用 GraphQL 和 MongoDB 定义 InputType 和 ObjectType 字段时使用自定义类型和类吗
【发布时间】:2022-10-08 05:44:05
【问题描述】:

我对这些堆栈相当陌生,因为我正在尝试使用它们来构建应用程序(GraphQL、NestJS 和使用 MongoDB 实现)。

我的模型有一个文件,我在其中导出了一个自定义类和类型以供以后使用,如下定义:

address.model.ts

@ObjectType()
export class myAddress {
    @Field(type => Int, { nullable: true })
    id?: number;
    @Field()
    name: string;
    @Field()
    company: string;
    @Field()
    street1: string;
    @Field()
    street2: string;
    @Field()
    city: string;
    @Field()
    state: string;
    @Field()
    zip: string;
    @Field()
    country: string;
    @Field()
    email: string;
    @Field()
    phone: string;
    @Field()
    verify: string[];
    @Field()
    notes: string;

遵循 NestJS 中用于 GraphQL 和 Mongo 集成的文档,我创建了一个输入和 dto 文件,我相信它可以填充字段。他们使用了一个简单的“猫”示例,但我想使用我自己定义的类。

我一直在尝试这样定义输入和 dto:

创建地址.dto.ts:

import { Field, ObjectType } from "@nestjs/graphql";
import { myAddress } from "../addresses.model";
@ObjectType()
export class CreateAddressDto {
    @Field(type => myAddress)
    readonly address: myAddress;
}

那么,在

地址.input.ts:

import { Field, InputType } from "@nestjs/graphql";
import { myAddress } from "../addresses.model";

@InputType()
export class AddressInput {
    @Field(type => myAddress)
    readonly address: myAddress;
};

这给我一个错误:

抛出新的 cannot_determine_output_type_error_1.CannotDetermineOutputTypeError(hostType); ^ 错误:无法确定“地址”的 GraphQL 输出类型。确保您的班级使用合适的装饰器进行装饰。 在 OutputTypeFactory.create

我相信我理解,但我的问题是:当我们想要创建这样的输入和 dto 文件时,我们可以使用自定义类和类型吗?还是 GraphQL 只能处理原始类型? (字符串,整数...)。

为了扩展我的情况,我想从其他包中的类创建一些自定义类。所以我不会自己写每个领域,而是会从其他包中借用模型。如果这有意义... 为了显示:

在 address.model.ts 中:

import { Field, Int, ObjectType } from "@nestjs/graphql";
import { Address } from '@easypost/api';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@ObjectType()
export class myAddress {
    @Field(type => Int, { nullable: true }) //makes it optional
    id?: number;

    @Field(type => Address, { nullable: true })
    address?: Address;

    @Field(type => String, { nullable: true })
    notes?: string;
};

export type AddressDocument = AddressDB & Document;

@Schema()
export class AddressDB {
    @Prop()
    address: myAddress;
}

export const AddressSchema = SchemaFactory.createForClass(AddressDB);

谢谢

【问题讨论】:

  • 可以,但只能引用 InputTypes 中的 InputTypes,并且只能引用 ObjectTypes 中的 ObjectTypes。反之亦然。

标签: mongodb graphql nestjs


【解决方案1】:

我敢打赌你已经知道你想要的答案,因为从那时起已经过去了 4 个月,但只是为了另一个发现这个问题的人。你可以添加你的

@Schema()
@ObjectType()
export class NeededSchema{
@Props()
@Field()
data: string;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多