-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathEmployeeController.java
More file actions
59 lines (49 loc) · 1.72 KB
/
EmployeeController.java
File metadata and controls
59 lines (49 loc) · 1.72 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 ch.etml.es.payroll.controllers;
import ch.etml.es.payroll.repositories.EmployeeRepository;
import ch.etml.es.payroll.entities.Employee;
import ch.etml.es.payroll.services.EmployeeService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
@RestController
@RequestMapping("/v1/employees")
public class EmployeeController {
private final EmployeeRepository repository;
EmployeeController(EmployeeRepository repository){
this.repository = repository;
}
/* curl sample :
curl -X GET localhost:8080/api/v1/employees | jq
*/
@GetMapping("")
List<Employee> all(){
return repository.findAll();
}
/* curl sample :
curl -X GET localhost:8080/api/v1/employees/1
*/
@GetMapping("/{id}")
Employee one(@PathVariable Long id){
return repository.findById(id)
.orElseThrow(() -> new EmployeeNotFoundException(id));
}
/* curl sample :
curl -i -X POST localhost:8080/api/v1/employees ^
-H "Content-type:application/json" ^
-d "{\"name\": \"Russel George\", \"role\": \"gardener\"}"
*/
@PostMapping("")
public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
Employee created = EmployeeService.create(employee);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.getId())
.toUri();
return ResponseEntity
.created(location)
.body(created);
}
}