'Using @Field and @Prop in the same class in NestJs is a bad practice?
I'm experiencing with NestJs, using @nestjs/mongoose and @nestjs/graphql
.
In NestJs docs, they describe both packages in detail, but they did not mention If it's possible to use both decorators in the same class. The team contributing to NestJS is amazing and I'm sure they also thought about having a single class for schemas and GraphQL types.
When I tried it, it was not working as expected I must say. But as I mentioned before this is the first time I'm using this.
My question is why not do so? or maybe It's even recommended to do so? It's very helpful to have one source of truth regarding types.
Here is a short block of code I tried and did not work as expected.
@Schema({
timestamps: true,
collection: 'users',
strict: true,
_id: true,
})
@ObjectType('BankAccount')
export class IUser {
_id!: Types.ObjectId
@Field(() => ID)
id?: string
@Field()
@Prop({ required: true })
username!: string
@Field()
@Prop({ required: true })
password!: string
}
export type UserDocument = IUser & Document
export const UserSchema = SchemaFactory.createForClass(IUser)
Solution 1:[1]
It is possible to combine your DTO (or GraphQL Object) with your DAO (in this case your mongoose schema) however, that strongly ties your API to your database and if one of them changes the other must too, which could be a breaking change, or you have to spend time separating out the DTO from the DAO. Sure it's a little bit of code duplication in the first place, but in the end it can end up saving time if you have to change the database often and want to keep from making breaking changes to your API.
In the end, it's a call for the dev team to make, so it's kind of opinionated, but I like keeping the DTO and DAO separate.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jay McDoniel |