I'm creating an app using microservice architecture with go and mongodb. Now I'm trying to make a crud with users, but I faced with a small problem. When I try to update the record nothing changes. I don't know what can be the problem, cuz I took it from official documentation.
So here's my code:
user_service.go
type UserService struct {
protos.UserServiceServer
}
func (s *UserService) Update(_ context.Context, request *protos.UpdateRequest) (*protos.GetResponse, error) {
resultUser, err := user.Update(request)
if err != nil {
return response.CreateErrorGetResponse("couldn't update user"), nil
}
return response.CreateGetResponse(resultUser), nil
}
user_funcs.go
func Update(request *protos.UpdateRequest) (*store.User, error) {
claims, err := jwt_func.DecodeJwt(request.Token)
if err != nil {
return nil, err
}
filter := bson.D{{"_id", claims.Id}}
update := parseRequest(request)
err = repository.Update(filter, bson.D{{"$set", update}})
if err != nil {
return nil, err
}
user, err := repository.GetById(claims.Id)
return user, nil
}
func parseRequest(request *protos.UpdateRequest) bson.D {
var update bson.D
if request.Nickname != "" {
updateBson(&update, "nickname", request.Nickname)
}
if request.PhoneNumber != "" {
updateBson(&update, "phone_number", request.PhoneNumber)
}
if request.Email != "" {
updateBson(&update, "email", request.Email)
}
if request.Password != "" {
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
updateBson(&update, "password", string(hashedPassword))
}
return update
}
func updateBson(data *bson.D, key string, value interface{}) {
*data = append(*data, bson.E{Key: key, Value: value})
}
user_repo.go
func Update(filter bson.D, updateData bson.D) error {
_, err := config.DBCollection.UpdateOne(config.DBContext, filter, updateData)
if err != nil {
config.ErrorConsoleLogger.Println("Error: couldn't update user")
return err
}
return nil
}
UserService.proto
message UpdateRequest {
string token = 1;
string nickname = 2;
string login = 3;
string email = 4;
string phoneNumber = 5;
string password = 6;
}
service UserService {
rpc Update(UpdateRequest) returns (GetResponse);
}
So what can be the problem? If you know, please tell me. I'd really appreciate it!