Best way to check if a graphql field is unique


Let’s imagine i have a schema like :
User {
id : ID
email : String
name :String
I would like to verify if the field “email” already exist in the database before doing a mutation.
I would like to avoid having 2 users with the same email.

How can i make sure of this uniqueness?
Should I create a logic first that does a graphql query and retrieve all the user with this email in the database and if the email already exists i dont execute the mutation?
Is there any Graphql type/feature that would declare the field “email” as unique and would return an error on the mutation request if the email exists?

What is the best way to make sure a field is unique?

Best regards

Hi @cyril36 :wave: uniqueness is, IMO, a property that belongs to your persistence layer. In addition, since email is personally-identifiable information (PII) it’s a risk for users if your clients are able to determine whether a given email address is associated with an account in your application. So I recommend validating uniqueness in your database and not on the client. When a mutation is executed on your GraphQL server, the database will return an error if any constraints are violated and that error can be reported to the user via the errors entry the server response.

1 Like