-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathUserController.java
More file actions
49 lines (39 loc) · 1.63 KB
/
Copy pathUserController.java
File metadata and controls
49 lines (39 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.user;
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.nio.file.Path;
import java.util.List;
@RestController
@RequestMapping("users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public ResponseEntity<List<User>> getAll(){
return ResponseEntity.ok(userRepository.findAll());
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user){
return new ResponseEntity<User>(this.userRepository.save(user), HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable int id, @RequestBody User user){
User userToUpdate = this.userRepository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found")
);
userToUpdate.setUsername(user.getUsername());
userToUpdate.setPassword(user.getPassword());
return new ResponseEntity<User>(this.userRepository.save(userToUpdate), HttpStatus.CREATED);
}
@DeleteMapping("/{id}")
public ResponseEntity<User> deleteUser(@PathVariable int id){
User userToDelete = this.userRepository.findById(id).orElseThrow(
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found")
);
this.userRepository.delete(userToDelete);
return ResponseEntity.ok(userToDelete);
}
}