I have a resolver to create a new user. This has a DTO which has an email field and which checks if this email is already taken by another user. Then this resolver calls a service which creates the user. The problem is that I don't know if I should do the verification at the service or DTO level via my custom decorator (IsUnique).
I'm wondering this in case I need to reuse my service in another module.
#Database verification via DTO or Service?
1 messages · Page 1 of 1 (latest)
Accessing the database from DTO / decorator will be difficult. Do the check in the service.
to me, DTOs shouldn't have such business logic
just input/output shape validation
Everything else should be done apart from DTOs
So you can have 2 DTOs (REST and graphql interfaces) reusing the same business rule
Depending or your ORM you can have it in your model decorators, here's what I have with typegoose :
@prop({ type: String, unique: true, required: true, match: /.+@.+\..+/ })
email: string
So, if you are using a pipe for data validation, you need to ask yourself if the existence of an email in the database is data validation or not. I don‘t personally believe so. It is business logic and a constraint. And, those decisions should be handled in a service IMHO.