Skip to content

Update UserService.java #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -65,4 +65,12 @@ public ResponseEntity<List<User>> getAllUser() {
List<User> allUser = userService.getAllUser();
return ResponseEntity.ok(allUser);
}

// update the user
@PutMapping("/{userId}")
public ResponseEntity<String> updateUser(@PathVariable String userId, @RequestBody User user) throws ResourceNotFoundException {
User updatedUser = userService.updateUser(userId, user);
String message = "User with ID " + userId + " has been successfully updated.";
return ResponseEntity.ok(message);
}
}
Original file line number Diff line number Diff line change
@@ -20,6 +20,7 @@ public interface UserService {

//TODO: delete
//TODO: update

// this method help us to update user in server
User updateUser(String userId,User user) throws ResourceNotFoundException;

}
Original file line number Diff line number Diff line change
@@ -75,4 +75,32 @@ public User getUser(String userId) {

return user;
}

// update the user
// step we use optional to avoid null pointer exception
// first we need user present with given user id in server then we get user .
// then update the user
@Override
public User updateUser(String userId, User user) throws ResourceNotFoundException {
Optional<User> optionalUser = userRepository.findById(userId);
if(optionalUser.isPresent()) {
User user1 = optionalUser.get();
if (user.getName() != null) {
user1.setName(user.getName());
}
if (user.getEmail() != null) {
user1.setEmail(user.getEmail());
}
if (user.getAbout() != null) {
user1.setAbout(user.getAbout());
}

return userRepository.save(user);
}
else{
throw new ResourceNotFoundException ("User not found with ID: " + userId);
}
}


}