【发布时间】:2019-07-04 11:21:05
【问题描述】:
编辑:我在下面实现,将其发布到GitHub 以供用户身份验证。
根据评论编辑:DTO 文件可以替换为 @nestjs/graphql 基于 GraphQL 类型生成的类吗?我可以通过生成这些类来创建 NestJS / MongoDB / Mongoose / GraphQL 应用程序,然后为我的 MongoDB Schema 扩展它们。然后,在这个问题之后,欢迎任何最佳实践意见,但将接受回答上述问题的答案。以下为原帖:
描述用户模型的最佳方式是什么?是定义 graphQL 类型并使用它来生成类来替换 dto 文件并导入 Mongoose 以用于 MongoDB 模式?下面我将解释我在做什么,以及什么可能会更好。我自己重复的文件数量似乎不可扩展。
以下是我描述同一用户的多种方式:
users.types.graphql - GraphQL 类型,包含创建用户输入、更新用户输入等。它包含以下内容:
type Mutation {
createUser(createUserInput: CreateUserInput): User
}
input CreateUserInput {
username: String
email: String
password: String
}
type User {
_id: String!
username: String
email: String
password: String
}
user.interfaces.ts - 描述 MongoDB Schema 和我的 user.service.ts 使用的用户类型,其中包含:
export interface IUser {
email: string;
password: string;
username: string;
}
user.schema.ts - MongoDB 架构。向 Mongoose 描述用户。它还扩展了user.interfaces.ts 和Document 中的用户界面,以公开用于严格类型检查的实例方法(我可以将.checkPassword 添加到IUserDocument):
export interface IUserDocument extends IUser, Document {
checkPassword(
password: string,
callback: (error?: Error, same?: boolean) => any,
): void;
}
export const UserSchema: Schema = new Schema(....
UserSchema.pre<IUserDocument>('save', function(next) {
UserSchema.methods.checkPassword = function(....
create-user.dto.ts 和各种dtos 用于每个操作。这些对于我上面描述输入的 GraphQl 类型文件来说似乎是多余的。这是dto:
export class CreateUserDto {
readonly email: string;
readonly password: string;
readonly username: string;
}
我想知道为我的用户模型提供一个真实数据的最佳做法是什么。我在想:
使用
GraphQLModule.forRoot({
definitions: {
path: join(process.cwd(), 'src/graphql.classes.ts'),
outputAs: 'class',
},
并将它用于我的接口和我的 dto 文件,因为它输出:
export class CreateUserInput {
username?: string;
email?: string;
password?: string;
}
export class User {
_id: number;
username?: string;
email?: string;
password?: string;
}
那时还需要dto 文件吗?它们不是只读的有关系吗?我可以将这些类自动拆分到我各自的文件夹(用户到用户文件夹,产品到产品文件夹)吗?
当我完成一个千篇一律的 NestJS、MongoDB、Passport-JWT、GraphQL 后端和用户身份验证后,我将发布一个公共 GitHub 链接,以便人们有一个参考(那里有一个使用 DTO)。
【问题讨论】:
-
这类问题不太适合,因为它要求的是意见而不是事实。 Pease 将其缩小为可以简洁回答的单个问题。请参阅help section 了解更多信息。
-
已编辑。查看新的第一行,谢谢。
-
客户端和服务器之间的数据传输肯定需要 DTO,但是您可以使用 Typegoose 进行打字,您会很好地满足打字要求并减少一点冗余。希望有帮助!
-
查看此链接到他们的文档。我相信 PartialType() 实用程序函数是您正在寻找的。 NestJS Mapped Types - PartialType
标签: mongodb mongoose graphql nestjs