|
| 1 | +package pl.codecouple.update.todo; |
| 2 | + |
| 3 | +import org.springframework.http.HttpStatus; |
| 4 | +import org.springframework.http.ResponseEntity; |
| 5 | +import org.springframework.web.bind.annotation.*; |
| 6 | + |
| 7 | +import java.net.URI; |
| 8 | +import java.util.Map; |
| 9 | + |
| 10 | +/** |
| 11 | + * Created by Krzysztof Chruściel. |
| 12 | + */ |
| 13 | +@RestController |
| 14 | +@RequestMapping("/todos") |
| 15 | +public class TodoController { |
| 16 | + |
| 17 | + private final TodoService todoService; |
| 18 | + |
| 19 | + public TodoController(TodoService todoService) { |
| 20 | + this.todoService = todoService; |
| 21 | + } |
| 22 | + |
| 23 | + @PostMapping |
| 24 | + @ResponseStatus(value = HttpStatus.CREATED, reason = "Todo created!") |
| 25 | + public void addNewTodo(@RequestBody Todo todo){ |
| 26 | + todoService.addNewTodo(todo); |
| 27 | + } |
| 28 | + |
| 29 | + @PutMapping("/{id}") |
| 30 | + public ResponseEntity<Void> updateTodo(@RequestBody Todo todo, @PathVariable Long id) throws TodoNotFound { |
| 31 | + Todo todoById = todoService.getTodoById(id); |
| 32 | + if(todoById == null){ |
| 33 | + todoService.addNewTodo(todo); |
| 34 | + return ResponseEntity.created(URI.create(String.format("/todos/%d", id))).build(); |
| 35 | + } |
| 36 | + todoService.update(todo); |
| 37 | + return ResponseEntity.noContent().build(); |
| 38 | + } |
| 39 | + |
| 40 | + @PatchMapping("/{id}") |
| 41 | + @ResponseStatus(value = HttpStatus.NO_CONTENT, reason = "Todo partial updated!") |
| 42 | + public void updateTodo(@RequestBody Map<String, Object> updates, @PathVariable Long id) throws TodoNotFound { |
| 43 | + Todo todo = todoService.getTodoById(id); |
| 44 | + if (todo == null) { |
| 45 | + throw new TodoNotFound(String.format("Todo with ID %d not exists!", id)); |
| 46 | + } |
| 47 | + partialUpdate(todo, updates); |
| 48 | + } |
| 49 | + |
| 50 | + private void partialUpdate(Todo todo, Map<String, Object> updates) { |
| 51 | + if (updates.containsKey("title")) { |
| 52 | + todo.setTitle((String) updates.get("title")); |
| 53 | + } |
| 54 | + if (updates.containsKey("description")) { |
| 55 | + todo.setDescription((String) updates.get("description")); |
| 56 | + } |
| 57 | + todoService.partialUpdated(todo); |
| 58 | + } |
| 59 | +} |
0 commit comments