11package com .example .easynotes .controller ;
22
3+ import com .example .easynotes .exception .ResourceNotFoundException ;
34import com .example .easynotes .model .Note ;
45import com .example .easynotes .repository .NoteRepository ;
56import org .springframework .beans .factory .annotation .Autowired ;
@@ -24,42 +25,38 @@ public List<Note> getAllNotes() {
2425 return noteRepository .findAll ();
2526 }
2627
27- @ GetMapping ("/notes/{id}" )
28- public ResponseEntity <Note > getNoteById (@ PathVariable (value = "id" ) Long noteId ) {
29- Note note = noteRepository .findOne (noteId );
30- if (note == null ) {
31- return ResponseEntity .notFound ().build ();
32- }
33- return ResponseEntity .ok ().body (note );
34- }
35-
3628 @ PostMapping ("/notes" )
3729 public Note createNote (@ Valid @ RequestBody Note note ) {
3830 return noteRepository .save (note );
3931 }
4032
33+ @ GetMapping ("/notes/{id}" )
34+ public Note getNoteById (@ PathVariable (value = "id" ) Long noteId ) {
35+ return noteRepository .findById (noteId )
36+ .orElseThrow (() -> new ResourceNotFoundException ("Note" , "id" , noteId ));
37+ }
38+
4139 @ PutMapping ("/notes/{id}" )
42- public ResponseEntity < Note > updateNote (@ PathVariable (value = "id" ) Long noteId ,
40+ public Note updateNote (@ PathVariable (value = "id" ) Long noteId ,
4341 @ Valid @ RequestBody Note noteDetails ) {
44- Note note = noteRepository . findOne ( noteId );
45- if ( note == null ) {
46- return ResponseEntity . notFound (). build ( );
47- }
42+
43+ Note note = noteRepository . findById ( noteId )
44+ . orElseThrow (() -> new ResourceNotFoundException ( "Note" , "id" , noteId ) );
45+
4846 note .setTitle (noteDetails .getTitle ());
4947 note .setContent (noteDetails .getContent ());
5048
5149 Note updatedNote = noteRepository .save (note );
52- return ResponseEntity . ok ( updatedNote ) ;
50+ return updatedNote ;
5351 }
5452
5553 @ DeleteMapping ("/notes/{id}" )
56- public ResponseEntity <Note > deleteNote (@ PathVariable (value = "id" ) Long noteId ) {
57- Note note = noteRepository .findOne (noteId );
58- if (note == null ) {
59- return ResponseEntity .notFound ().build ();
60- }
54+ public ResponseEntity <?> deleteNote (@ PathVariable (value = "id" ) Long noteId ) {
55+ Note note = noteRepository .findById (noteId )
56+ .orElseThrow (() -> new ResourceNotFoundException ("Note" , "id" , noteId ));
6157
6258 noteRepository .delete (note );
59+
6360 return ResponseEntity .ok ().build ();
6461 }
6562}
0 commit comments