-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathUserController.java
More file actions
49 lines (37 loc) · 1.63 KB
/
Copy pathUserController.java
File metadata and controls
49 lines (37 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
package com.booleanuk.api.controllers;
import com.booleanuk.api.models.User;
import com.booleanuk.api.repositories.UserRepository;
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("users")
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
return new ResponseEntity<>(this.userRepository.findAll(), HttpStatus.OK);
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
return new ResponseEntity<>(this.userRepository.save(user), HttpStatus.OK);
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable(name = "id") int id, @RequestBody User user) {
User toUpdate = this.userRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
toUpdate.setName(user.getName());
return new ResponseEntity<>(this.userRepository.save(toUpdate), HttpStatus.CREATED);
}
@DeleteMapping("/{id}")
public ResponseEntity<User> deleteUser(@PathVariable int id) {
User toDelete = this.userRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"));
this.userRepository.delete(toDelete);
return ResponseEntity.ok(toDelete);
}
}