-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathCustomerController.java
More file actions
58 lines (50 loc) · 2.13 KB
/
CustomerController.java
File metadata and controls
58 lines (50 loc) · 2.13 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
package com.booleanuk.api.cinema.customers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@RestController
@RequestMapping("customers")
public class CustomerController {
@Autowired
private CustomerRepository customerRepository;
@ResponseStatus(HttpStatus.OK)
@GetMapping("{id}")
public Customer getOneCustomer(@PathVariable int id) {
return this.customerRepository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found.")
);
}
@ResponseStatus(HttpStatus.OK)
@GetMapping
public List<Customer> getAllCustomers() {
return this.customerRepository.findAll();
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public Customer createCustomer(@RequestBody Customer customer) {
Customer newCustomer = new Customer(customer.getName(), customer.getEmail(), customer.getPhone());
return this.customerRepository.save(newCustomer);
}
@ResponseStatus(HttpStatus.CREATED)
@PutMapping("{id}")
public Customer updateCustomer(@RequestBody Customer customer, @PathVariable int id) {
Customer customerToUpdate = this.customerRepository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found.")
);
customerToUpdate.setName(customer.getName());
customerToUpdate.setEmail(customer.getEmail());
customerToUpdate.setPhone(customer.getPhone());
return this.customerRepository.save(customerToUpdate);
}
@ResponseStatus(HttpStatus.OK)
@DeleteMapping("{id}")
public Customer deleteCustomer(@PathVariable int id) {
Customer customerToDelete = this.customerRepository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found.")
);
this.customerRepository.delete(customerToDelete);
return customerToDelete;
}
}