-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathCustomerController.java
More file actions
47 lines (38 loc) · 1.83 KB
/
CustomerController.java
File metadata and controls
47 lines (38 loc) · 1.83 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
package com.booleanuk.api.cinema.controllers;
import com.booleanuk.api.cinema.models.Customer;
import com.booleanuk.api.cinema.payload.response.CustomerListResponse;
import com.booleanuk.api.cinema.repositories.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.util.List;
@RestController
@RequestMapping("customers")
public class CustomerController {
@Autowired
private CustomerRepository repository;
@GetMapping
public List<Customer> getAll(){
return this.repository.findAll();
}
@PostMapping
public ResponseEntity<Customer> createCustomer(@RequestBody Customer customer){
return new ResponseEntity<Customer>(this.repository.save(customer), HttpStatus.CREATED);
}
@PutMapping("{id}")
public ResponseEntity<Customer> updateCustomer(@PathVariable int id, @RequestBody Customer customer){
Customer customerToUpdate = this.repository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"));
customerToUpdate.setName(customer.getName());
customerToUpdate.setEmail(customer.getEmail());
customerToUpdate.setPhone(customer.getPhone());
return new ResponseEntity<>(this.repository.save(customerToUpdate), HttpStatus.CREATED);
}
@DeleteMapping("{id}")
public ResponseEntity<Customer> DeleteCustomer(@PathVariable int id) {
Customer customerToDelete = this.repository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"));
this.repository.delete(customerToDelete);
return ResponseEntity.ok(customerToDelete);
}
}