86 lines
2.9 KiB
Java
86 lines
2.9 KiB
Java
package pl.edu.amu.wmi.bookapi.api;
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.security.core.context.SecurityContextHolder;
|
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
|
import org.springframework.web.bind.annotation.GetMapping;
|
|
import org.springframework.web.bind.annotation.PatchMapping;
|
|
import org.springframework.web.bind.annotation.PathVariable;
|
|
import org.springframework.web.bind.annotation.PostMapping;
|
|
import org.springframework.web.bind.annotation.RequestBody;
|
|
import org.springframework.web.bind.annotation.RequestMapping;
|
|
import org.springframework.web.bind.annotation.RequestParam;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
import pl.edu.amu.wmi.bookapi.api.dto.BookDto;
|
|
import pl.edu.amu.wmi.bookapi.service.BookService;
|
|
|
|
import javax.validation.Valid;
|
|
|
|
@RestController
|
|
@RequestMapping("/api/books")
|
|
public class BookController {
|
|
|
|
BookService bookService;
|
|
|
|
@Autowired
|
|
public BookController(BookService bookService) {
|
|
this.bookService = bookService;
|
|
}
|
|
|
|
@GetMapping
|
|
public ResponseEntity getBooks() {
|
|
return ResponseEntity.ok().body(bookService.findAllForUser(
|
|
getUserName()
|
|
));
|
|
}
|
|
|
|
@GetMapping("/public")
|
|
public ResponseEntity getAllBooks() {
|
|
return ResponseEntity.ok().body(
|
|
bookService.findAll()
|
|
);
|
|
}
|
|
|
|
@PatchMapping("/{bookId}")
|
|
public ResponseEntity updateBook(@RequestBody BookDto bookDto, @PathVariable String bookId) {
|
|
String username = getUserName();
|
|
System.out.println("Book dto");
|
|
System.out.println(bookDto);
|
|
return ResponseEntity.ok(
|
|
bookService.updateBook(bookId ,username, bookDto)
|
|
);
|
|
}
|
|
|
|
@DeleteMapping("/{bookId}")
|
|
public ResponseEntity deleteBook(@PathVariable String bookId) {
|
|
System.out.println("Deleting book for user " + getUserName() + " of Id " + bookId);
|
|
bookService.deleteBook(
|
|
getUserName(),
|
|
bookId
|
|
);
|
|
|
|
return ResponseEntity.ok().build();
|
|
}
|
|
|
|
@PostMapping
|
|
public ResponseEntity addBook(@RequestBody @Valid BookDto bookDto) {
|
|
bookService.saveBook(getUserName(), bookDto);
|
|
return ResponseEntity.ok().build();
|
|
}
|
|
|
|
@PostMapping("/image")
|
|
public ResponseEntity addBookAsImage(
|
|
@RequestParam("file") MultipartFile imageFile,
|
|
@RequestParam("author") String author,
|
|
@RequestParam("title") String title) throws Exception {
|
|
bookService.handleImageUpload(imageFile, author, title, getUserName());
|
|
return ResponseEntity.ok().build();
|
|
}
|
|
|
|
private String getUserName() {
|
|
return SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
|
|
}
|
|
}
|