-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathAuthorController.java
More file actions
59 lines (49 loc) · 2.43 KB
/
Copy pathAuthorController.java
File metadata and controls
59 lines (49 loc) · 2.43 KB
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
package com.booleanuk.api.controller;
import com.booleanuk.api.model.Author;
import com.booleanuk.api.repository.AuthorRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@RestController
@RequestMapping("authors")
public class AuthorController {
private final AuthorRepository repository;
public AuthorController(AuthorRepository repository) {
this.repository = repository;
}
@GetMapping
public ResponseEntity<List<Author>> getAll() {
return ResponseEntity.ok(this.repository.findAll());
}
@GetMapping("{id}")
public ResponseEntity<Author> getById(@PathVariable("id") Integer id) {
Author author = this.repository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Could not find author with that id."));
return ResponseEntity.ok(author);
}
record PostAuthor(String first_name, String last_name, String email, boolean alive) {}
//@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public ResponseEntity<Author> create(@RequestBody PostAuthor request) {
Author author = new Author(request.first_name(), request.last_name(), request.email(), request.alive());
return new ResponseEntity<>(this.repository.save(author), HttpStatus.CREATED);
}
@PutMapping("{id}")
public ResponseEntity<Author> updateAuthor(@PathVariable int id, @RequestBody PostAuthor author) {
Author authorToUpdate = this.repository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Could not find author with that id."));
authorToUpdate.setFirstName(author.first_name());
authorToUpdate.setLastName(author.last_name());
authorToUpdate.setEmail(author.email());
authorToUpdate.setAlive(author.alive());
return new ResponseEntity<>(this.repository.save(authorToUpdate), HttpStatus.CREATED);
}
@DeleteMapping("{id}")
public ResponseEntity<Author> deleteAuthor(@PathVariable int id) {
Author authorToDelete = this.repository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Could not find author with that id."));
this.repository.delete(authorToDelete);
return ResponseEntity.ok(authorToDelete);
}
}