RoomController PUT fixed

This commit is contained in:
Claudio Maggioni 2020-03-23 16:42:33 +01:00
parent 1204451e47
commit f4d6a3f3c7

View File

@ -33,40 +33,50 @@ public class RoomController {
return roomRepository.findById(id).orElseThrow(NotFoundException::new); return roomRepository.findById(id).orElseThrow(NotFoundException::new);
} }
private Room save(final RoomSaveRequest r, final Principal principal, boolean setWhenNull) { @PostMapping
Room newRoom = new Room(); public @ResponseBody Room create(
@Valid @RequestBody RoomSaveRequest r, final Principal principal) {
final String username = principal.getName(); final String username = principal.getName();
final Long userId = userRepository.findByUsername(username).getId(); final Long userId = userRepository.findByUsername(username).getId();
final String img = r.getImage(); final String img = r.getImage();
final Room.Icon icon = r.getIcon(); final Room.Icon icon = r.getIcon();
final Room newRoom = new Room();
newRoom.setUserId(userId); newRoom.setUserId(userId);
newRoom.setName(r.getName()); newRoom.setName(r.getName());
if (img != null) { newRoom.setImage(img);
newRoom.setImage(img); newRoom.setIcon(icon);
} else if (setWhenNull) {
newRoom.setImage(null);
}
if (icon != null) {
newRoom.setIcon(icon);
} else if (setWhenNull) {
newRoom.setIcon(null);
}
return roomRepository.save(newRoom); return roomRepository.save(newRoom);
} }
@PostMapping @PutMapping("/{id}")
public @ResponseBody Room create(
@Valid @RequestBody RoomSaveRequest r, final Principal principal) {
return this.save(r, principal, true);
}
@PutMapping
public @ResponseBody Room update( public @ResponseBody Room update(
@Valid @RequestBody RoomSaveRequest r, final Principal principal) { @PathVariable("id") long id, @RequestBody RoomSaveRequest r, final Principal principal)
return this.save(r, principal, false); throws NotFoundException {
final Room newRoom =
roomRepository
.findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new);
final String img = r.getImage();
final Room.Icon icon = r.getIcon();
if (r.getName() != null) {
newRoom.setName(r.getName());
}
if ("".equals(img)) {
newRoom.setImage(null);
} else if (img != null) {
newRoom.setImage(img);
}
if (icon != null) {
newRoom.setIcon(icon);
}
return roomRepository.save(newRoom);
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")