Skip to content

Instantly share code, notes, and snippets.

@koblas
Created July 30, 2018 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koblas/7c69b804d033373b907a815a54afe946 to your computer and use it in GitHub Desktop.
Save koblas/7c69b804d033373b907a815a54afe946 to your computer and use it in GitHub Desktop.
GraphQL user_update code separation
// UpdateUser save user updates to the DB
func (svc *userService) UpdateUser(ctx context.Context, user *model.User, args UpdateUserInput) (*model.User, error) {
update := make(map[string]interface{})
if args.Password != nil {
user.HashPassword(*args.Password)
update["password"] = user.Password
}
if args.Name != nil && *args.Name != user.Name {
update["name"] = *args.Name
}
if args.Email != nil && *args.Email != user.Email {
update["email"] = *args.Email
}
if len(update) == 0 {
return user, nil
}
update["updated_at"] = "NOW()"
err := svc.db.Collection("users").Find(db.Cond{"id": user.ID}).Update(update)
if err != nil {
return user, err
}
if args.Name != nil {
user.Name = *args.Name
}
if args.Email != nil {
user.Email = *args.Email
}
return user, nil
}
mutationConfig.AddFieldConfig("user_update", &graphql.Field{
Type: userUpdateResponseQL,
Args: graphql.FieldConfigArgument{
"input": &graphql.ArgumentConfig{
Type: &graphql.NonNull{
OfType: userUpdateInputQL,
},
},
},
Resolve: wrapIsAuth(wrapGraphQL(func(ctx context.Context, input struct {
Input struct {
Name *string `valid:"length(1|100)~Must not be empty"`
Email *string `valid:"email~Invalid email address"`
Password *string
Newpass *string `valid:"length(6|80)~Must be a minimum of 6 characters"`
}
}, validationErrors []*ValidationError) (interface{}, error) {
logger := service.LoggerFromContext(ctx)
data := input.Input
userService := service.UserServiceFromContext(ctx)
user, _ := ctx.Value(contextkey.User).(*model.User)
if data.Password != nil && user.ComparePassword(*data.Password) != nil {
validationErrors = append(validationErrors, &ValidationError{
"password", "Incorrect password",
})
}
if data.Newpass != nil && data.Password == nil {
validationErrors = append(validationErrors, &ValidationError{
"password", "Password is required",
})
}
if len(validationErrors) != 0 {
logger.WithField("validationErrors", validationErrors).Info("Validation error")
return userUpdateResponse{ValidationErrors: validationErrors}, nil
}
user, err := userService.UpdateUser(ctx, user, service.UpdateUserInput{
Name: data.Name,
Email: data.Email,
Password: data.Newpass,
})
if err != nil {
return nil, err
}
return userUpdateResponse{User: user}, nil
})),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment