-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathCustomerController.java
More file actions
70 lines (56 loc) · 2.69 KB
/
CustomerController.java
File metadata and controls
70 lines (56 loc) · 2.69 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
60
61
62
63
64
65
66
67
68
69
package com.booleanuk.api.cinema.controller;
import com.booleanuk.api.cinema.model.Customer;
import com.booleanuk.api.cinema.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
@RestController
@RequestMapping("customers")
public class CustomerController {
@Autowired
private CustomerRepository customerRepository;
@PostMapping
public ResponseEntity<Customer> createCustomer(@RequestBody Customer customer) {
try {
customer.setCreatedAt(LocalDateTime.now());
customer.setUpdatedAt(LocalDateTime.now());
return new ResponseEntity<>(this.customerRepository.save(customer), HttpStatus.CREATED);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Could not save the customer: " + e.getMessage());
}
}
@GetMapping
public ResponseEntity<List<Customer>> getAllCustomers() {
return ResponseEntity.ok(this.customerRepository.findAll());
}
@GetMapping("/{id}")
public ResponseEntity<Customer> getOneCustomer(@PathVariable int id) {
Customer customer = this.customerRepository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer with ID " + id + " not found.")
);
return ResponseEntity.ok(customer);
}
@PutMapping("/{id}")
public ResponseEntity<Customer> updateCustomer(@PathVariable int id, @RequestBody Customer customer) {
Customer customerToUpdate = this.customerRepository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer with ID " + id + " not found.")
);
customerToUpdate.setName(customer.getName());
customerToUpdate.setEmail(customer.getEmail());
customerToUpdate.setPhone(customer.getPhone());
customerToUpdate.setUpdatedAt(LocalDateTime.now());
return new ResponseEntity<>(this.customerRepository.save(customerToUpdate), HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteCustomer(@PathVariable int id) {
Customer customerToDelete = this.customerRepository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer with ID " + id + " not found.")
);
this.customerRepository.delete(customerToDelete);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}