1
1
package com .example .easynotes .controller ;
2
2
3
+ import com .example .easynotes .exception .ResourceNotFoundException ;
3
4
import com .example .easynotes .model .Note ;
4
5
import com .example .easynotes .repository .NoteRepository ;
5
6
import org .springframework .beans .factory .annotation .Autowired ;
@@ -24,42 +25,38 @@ public List<Note> getAllNotes() {
24
25
return noteRepository .findAll ();
25
26
}
26
27
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
-
36
28
@ PostMapping ("/notes" )
37
29
public Note createNote (@ Valid @ RequestBody Note note ) {
38
30
return noteRepository .save (note );
39
31
}
40
32
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
+
41
39
@ PutMapping ("/notes/{id}" )
42
- public ResponseEntity < Note > updateNote (@ PathVariable (value = "id" ) Long noteId ,
40
+ public Note updateNote (@ PathVariable (value = "id" ) Long noteId ,
43
41
@ 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
+
48
46
note .setTitle (noteDetails .getTitle ());
49
47
note .setContent (noteDetails .getContent ());
50
48
51
49
Note updatedNote = noteRepository .save (note );
52
- return ResponseEntity . ok ( updatedNote ) ;
50
+ return updatedNote ;
53
51
}
54
52
55
53
@ 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 ));
61
57
62
58
noteRepository .delete (note );
59
+
63
60
return ResponseEntity .ok ().build ();
64
61
}
65
62
}
0 commit comments