我是GraphQL的新手。我正在使用Graphene-Django并且有一个名为CreateUser
的变异。它需要三个参数username
,email
,password
。
如何验证数据并返回多个错误?
我想要这样的东西回来了。
{
"name":[
"Ensure this field has at least 2 characters."
],
"email":[
"This field may not be blank."
],
"password":[
"This field may not be blank."
]
}
所以我可以像这样在表单上呈现错误:
到目前为止我的代码:
from django.contrib.auth.models import User as UserModel
from graphene_django import DjangoObjectType
import graphene
class User(DjangoObjectType):
class Meta:
model = UserModel
only_fields = 'id', 'username', 'email'
class Query(graphene.ObjectType):
users = graphene.List(User)
user = graphene.Field(User, id=graphene.Int())
def resolve_users(self, info):
return UserModel.objects.all()
def resolve_user(self, info, **kwargs):
try:
return UserModel.objects.get(id=kwargs['id'])
except (UserModel.DoesNotExist, KeyError):
return None
class CreateUser(graphene.Mutation):
class Arguments:
username = graphene.String()
email = graphene.String()
password = graphene.String()
user = graphene.Field(User)
def mutate(self, info, username, email, password):
user = UserModel.objects.create_user(username=username, email=email, password=password)
return CreateUser(user=user)
class Mutation(graphene.ObjectType):
create_user = CreateUser.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
答案 0 :(得分:1)
模式中的模型错误,主要是使用联合。
以SDL格式:
type RegisterUserSuccess {
user: User!
}
type FieldError {
fieldName: String!
errors: [String!]!
}
type RegisterUserError {
fieldErrors: [FieldError!]!
nonFieldErrors: [String!]!
}
union RegisterUserPayload = RegisterUserSuccess | RegisterUserError
mutation {
registerUser(name: String, email: String, password: String): RegisterUserPayload!
}