通过resolve 方法中的验证逻辑,您可以完全控制生成的用户错误。这是一个例子:
// data/mutations/createUser.js
import {
GraphQLObjectType as ObjectType,
GraphQLNonNull as NonNull,
GraphQLList as List,
GraphQLString as StringType
} from 'graphql';
import validator from 'validator';
import UserType from '../types/UserType';
export default {
type: new ObjectType({
name: 'CreateUserResult',
fields: {
user: { type: UserType },
errors: { type: new NonNull(new List(StringType)) }
}
}),
args: {
email: { type: new NonNull(StringType) },
password: { type: new NonNull(StringType) }
},
resolve(_, { email, password }) {
let user = null;
let errors = [];
if (validator.isNull(email)) {
errors.push(...['email', 'The email filed must not be empty.']);
} else if (!validator.isLength(email, { max: 100})) {
errors.push(...['email', 'The email must be at a max 100 characters long.']);
}
// etc.
return { user, errors };
}
};
请参阅我关于此主题的博文 - Validation and User Errors in GraphQL Mutations
或者,创建type UserErrorType { key: String!, message: String! },在编译要返回给调用者的用户错误列表时,可以使用它来代替纯字符串。
GraphQL 查询
mutation {
createUser(email: "hello@tarkus.me", password: "Passw0rd") {
user { id, email },
errors { key, message }
}
}
查询响应
{
data: {
user: null,
errors: [
{ key: '', message: 'Failed to create a new user account.' },
{ key: 'email', message: 'User with this email already exists.' }
]
}
}