Skip to content

Commit 66c4579

Browse files
author
Jose Manuel De Pablo Cobo
committed
API Rest for OrderP entity. GET, POST, PUT and DELETE.
1 parent 3b47fc1 commit 66c4579

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.youdemy.controller;
2+
3+
import java.util.Optional;
4+
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.dao.EmptyResultDataAccessException;
7+
import org.springframework.http.HttpStatus;
8+
import org.springframework.http.ResponseEntity;
9+
import org.springframework.web.bind.annotation.*;
10+
11+
import com.youdemy.model.OrderP;
12+
import com.youdemy.service.OrderPService;
13+
14+
@RestController
15+
@RequestMapping("/api/orders")
16+
public class OrderPRestController {
17+
18+
@Autowired
19+
private OrderPService orderService;
20+
21+
@GetMapping("/{id}")
22+
public ResponseEntity<OrderP> getOrder(@PathVariable long id) {
23+
24+
Optional<OrderP> order = orderService.findById(id);
25+
if (order.isPresent()) {
26+
OrderP dbOrder = order.get();
27+
return new ResponseEntity<>(dbOrder, HttpStatus.OK);
28+
}else {
29+
return new ResponseEntity<>(HttpStatus.NOT_FOUND); // trying access to not present resource
30+
}
31+
}
32+
33+
@PostMapping("/")
34+
@ResponseStatus(HttpStatus.CREATED)
35+
public OrderP createBook(@RequestBody OrderP order) {
36+
37+
orderService.save(order);
38+
39+
return order;
40+
}
41+
42+
@PutMapping("/{id}")
43+
public ResponseEntity<Optional<OrderP>> replaceOrder(@PathVariable long id, @RequestBody OrderP newOrder) {
44+
Optional<OrderP> put = orderService.findById(id);
45+
46+
if (put != null) {
47+
newOrder.setId(id);
48+
orderService.save(newOrder);
49+
return ResponseEntity.ok(put);
50+
} else {
51+
return ResponseEntity.notFound().build();
52+
}
53+
}
54+
55+
@DeleteMapping("/{id}")
56+
public ResponseEntity<OrderP> deleteOrder(@PathVariable long id) {
57+
58+
try {
59+
orderService.delete(id);
60+
return new ResponseEntity<>(null, HttpStatus.OK);
61+
62+
} catch (EmptyResultDataAccessException e) {
63+
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
64+
}
65+
}
66+
}

backend/src/main/java/com/youdemy/security/WebSecurityConfig.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ protected void configure(HttpSecurity http) throws Exception {
4848

4949
// H2 Console access without csrf
5050
http.csrf().ignoringAntMatchers("/h2-console/**");
51+
http.csrf().ignoringAntMatchers("/api/**");
5152
http.headers().frameOptions().sameOrigin();
5253

5354
// Sign in form

0 commit comments

Comments
 (0)