Skip to content

Commit 43771f2

Browse files
feat: add functionality to update existing users
1 parent 84ac44b commit 43771f2

File tree

1 file changed

+51
-3
lines changed

1 file changed

+51
-3
lines changed

server/user/src/main/java/meet_at_mensa/user/UserController.java

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,15 @@
44

55
import org.springframework.web.bind.annotation.RestController;
66
import org.springframework.web.bind.annotation.RequestMapping;
7+
import org.springframework.web.bind.annotation.PathVariable;
78
import org.springframework.web.bind.annotation.RequestBody;
89
import org.springframework.web.bind.annotation.GetMapping;
910
import org.springframework.web.bind.annotation.PostMapping;
11+
import org.springframework.web.server.ResponseStatusException;
12+
import org.springframework.http.HttpStatus;
13+
14+
import java.util.UUID;
15+
import java.util.Map;
1016

1117
@RestController
1218
public class UserController {
@@ -15,16 +21,58 @@ public class UserController {
1521
@Autowired // This is auto-implemented by spring
1622
private UserRepository userRepository;
1723

18-
// Responds to get requests on /users/all with a list of all users
24+
// Show all users in database
25+
// TODO: Remove in production
1926
@GetMapping(path="/debug/users/all")
2027
public Iterable<User> getAllUsers() {
2128
return userRepository.findAll();
2229
}
2330

2431
// Create a new user when provided with json formatted data
25-
@PostMapping(path="/api/users/new")
32+
@PostMapping(path="/api/users/create")
2633
public User createUser(@RequestBody User user) {
2734
return userRepository.save(user);
2835
}
2936

30-
}
37+
// Return user information
38+
@GetMapping(path="/api/users/get/{userID}")
39+
public User getUser(@PathVariable UUID userID) {
40+
return userRepository.findById(userID)
41+
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
42+
}
43+
44+
// Update user information
45+
@PostMapping(path="api/users/edit/{userID}")
46+
public User editUser(@PathVariable UUID userID, @RequestBody Map<String, String> update) {
47+
48+
// find user
49+
User user = userRepository.findById(userID)
50+
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
51+
52+
// Update values if present in payload
53+
if (update.containsKey("email")) {
54+
user.setEmail(update.get("email"));
55+
}
56+
57+
if (update.containsKey("name")) {
58+
user.setName(update.get("name"));
59+
}
60+
61+
if (update.containsKey("gender")) {
62+
user.setGender(update.get("gender"));
63+
}
64+
65+
if (update.containsKey("degree")) {
66+
user.setDegree(update.get("degree"));
67+
}
68+
69+
if (update.containsKey("birthday")) {
70+
// implement later
71+
}
72+
73+
// Save to Database and Return
74+
return userRepository.save(user);
75+
76+
}
77+
78+
}

0 commit comments

Comments
 (0)