来自 Laravel 背景,我尝试进入 node.js/graphQL/MongoDB 并偶然发现 nest.js
看起来很不错的框架。所以我尝试建立一个简单的 GraphQL API 来测试和理解它是如何工作的。因此,我为用户创建了一个 Mongoose 模式以及一个模型( type-graphql
)和一个 DTO
用于通过突变创建这样的用户。
这工作得很好,但后来我想在用户中添加一个名为 settings 的嵌套对象来尝试这是如何工作的,但我根本没有得到它,也没有找到任何 nest.js
或 type-graphql
这种实现的具体例子。使用 nest.js
的“代码优先”方法这根本不可行吗? ?因为模式生成器在编译时总是给我一个错误说:
"UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL output type for settings".
用户模型.ts
import { Field, ID, ObjectType } from 'type-graphql'
import UserSettingsType from './user.settings.type'
@ObjectType()
export class User {
@Field((type) => ID)
id: string
@Field()
email: string
@Field((type) => UserSettingsType)
settings: {}
}
user.settings.type.ts
import { Field, ObjectType } from 'type-graphql'
@ObjectType()
export class UserSettings {
@Field()
theme: string
@Field()
description?: string
@Field((type) => [String])
visited: string[]
}
新用户.input.ts
import { IsOptional, IsEmail, IsBoolean, Length, MaxLength, IsArray } from 'class-validator'
import { Field, InputType } from 'type-graphql'
import UserSettingsType from '../graphql/user.settings.type'
@InputType()
export class NewUserInput {
@Field()
@IsEmail()
email: string
@Field((type) => UserSettingsType)
@IsOptional()
@IsArray()
settings: {}
}
如您所见,我在单独的文件中定义了一个新类型 UserSettings(遵循
nest.js
的最佳实践)并将其分配为 User 模型和新用户 DTO 类中的一个类型。为 DTO class
抛出错误(不适用于模型),如果我将其更改为 [String] 之类的内容而不是 UserSettingsType,则它正在编译。我不确定您是否需要解析器或服务/ Mongoose 逻辑来解决这个实际问题,如果是这样的话,我当然也可以发布!
最佳答案
从 express 迁移到 nestjs 时遇到了类似的问题。
看完docs意识到问题不是嵌套对象,而是错误的导入。
您应该使用 @nestjs/graphql
进口而不是 type-graphql
.
例如。
// changes this
import { Field, ID, ObjectType } from 'type-graphql'
// to
import { Field, ID, ObjectType } from '@nestjs/graphql'
同样适用于来自
type-graphql
的任何其他导入
关于node.js - 模式生成器无法确定 DTO 中自定义对象的 GraphQL 输出类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56885199/