I am using graphene-django
instead of rest api
(rest framework). I am working on user registration. In the rest framework, validation was done in serializers part but when using graphene
how do i validate and handle error for passing meaningful status to client?
Here is the registration code
class Register(graphene.Mutation):
class Arguments:
email = graphene.String(required=True)
password = graphene.String(required=True)
password_repeat = graphene.String(required=True)
user = graphene.Field(UserQuery)
success = graphene.Boolean()
errors = graphene.List(graphene.String)
@staticmethod
def mutate(self, info, email, password, password_repeat):
if password == password_repeat:
try:
user = User.objects.create(email=email)
user.set_password(password)
user.is_active = False
user.full_clean()
user.save()
return Register(success=True, user=user)
except ValidationError as e:
import pdb
pdb.set_trace()
return Register(success=False, errors=[e])
return Register(success=False, errors=['password', 'password is not matching'])
one example can be validation for if user with email already exists
The easiest way looks like:
@staticmethod
def mutate(root, info, email, password, password_repeat):
errors = []
if password == password_repeat:
errors.append('password_is_not_matching')
if User.objects.filter(email=email).exists():
errors.append('email_is_already_registred')
if len(errors) == 0:
try:
user = User.objects.create(email=email)
user.set_password(password)
user.is_active = False
user.full_clean()
user.save()
return Register(success=True, user=user)
except ValidationError as e:
import pdb
pdb.set_trace()
return Register(success=False, errors=[e])
return Register(success=False, errors=errors)
But problems may appear if you make a lot of such checks - code becomes more complicated and it's harder to figure out what actually mutations do.
For more information read this article.