-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathProductController.java
More file actions
52 lines (41 loc) · 1.63 KB
/
ProductController.java
File metadata and controls
52 lines (41 loc) · 1.63 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
package com.booleanuk.api;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@RestController
@RequestMapping("products")
public class ProductController {
private ProductRepository productRepository;
public ProductController(){
this.productRepository = new ProductRepository();
}
@GetMapping List<Product> getAll(@RequestParam(required = false) String category){
return this.productRepository.findAll(category);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Product create(@RequestBody Product product){
this.productRepository.create(product.getName(), product.getCategory(), product.getPrice());
return product;
}
@GetMapping("/{id}")
public Product getSpecificProduct(@PathVariable int id){
return this.productRepository.findSpecificProduct(id);
}
@DeleteMapping("/{id}")
public Product deleteProduct(@PathVariable int id){
return this.productRepository.delete(id);
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.CREATED)
public Product updateProduct(@PathVariable int id, @RequestBody Product product){
Product newProduct = this.productRepository.update(id, product);
if(newProduct == null){
for (int i = 0; i < productRepository.getProducts().size(); i++){
}
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "The product with the ID: " + id + " could not be found in repository");
}
return newProduct;
}
}