-
Notifications
You must be signed in to change notification settings - Fork 6
/
LibraryRestController.java
97 lines (76 loc) · 2.83 KB
/
LibraryRestController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package io.company.library;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("api")
public class LibraryRestController {
//here we are creating our end-point rest API
@Autowired
BookService bookservice;
//CRUD: read
@GetMapping("books")
public Iterable<Book> getAllBooks() {
//
return bookservice.getAllBooks();
}
//CRUD: read, find one book by id
@GetMapping("getBook")
public Book findBookById(Long id){
//
Optional<Book> bookFound = bookservice.findBookById(id);
if (bookFound.isPresent()) return bookFound.get();
return null;
}
//CRUD: create
@PostMapping(path="addBook", consumes = "application/JSON")
public Book addBook(@RequestBody Book book){
//
Book bookCreated = bookservice.createBook(book);
return bookCreated ;
}
//CRUD: delete
@DeleteMapping("deleteBook")
public ResponseEntity<Book> deleteBook (@RequestParam Long id) {
//
HttpHeaders headers = new HttpHeaders();
headers.add("operation","deleteBook");
headers.add("version","api 1.0");
Optional<Book> bookFound = bookservice.findBookById(id);
boolean isBook = bookFound.isPresent();
if(isBook) {
//Optional<Book> deletedBook = bookservice.deleteBookById(id);
bookservice.deleteBookById(id);
headers.add("operationStatus","deleted");
return ResponseEntity.accepted().headers(headers).body(bookFound.get());
} else return ResponseEntity.accepted().body(null);
}
//CRUD: update
@PutMapping("/updateBook/{id}")
public ResponseEntity<Book> updateBook (@PathVariable Long id, @RequestBody Book dataBook) {
Optional<Book> bookFound = bookservice.findBookById(id);
if (bookFound.isPresent()) {
Book bookToUpdate = bookFound.get();
//
if (dataBook.getTitle() != null) {
bookToUpdate.setTitle(dataBook.getTitle());
}
Book bookUpdated = bookservice.updateBook(bookToUpdate);
return ResponseEntity.accepted().body(bookUpdated);
} else
return ResponseEntity.accepted().body(null);
}
//CRUD: delete book by title
@DeleteMapping("deleteBookByTitle")
public ResponseEntity<Book> deleteBookByTitle (@RequestParam String title) {
//
HttpHeaders headers = new HttpHeaders();
headers.add("operation","deleteBookByTitle");
headers.add("version","api 1.0");
//findBookByTitle(String title)
//deleteBookByTitle(String title)
return null;
}
}