44
55import org .springframework .web .bind .annotation .RestController ;
66import org .springframework .web .bind .annotation .RequestMapping ;
7+ import org .springframework .web .bind .annotation .PathVariable ;
78import org .springframework .web .bind .annotation .RequestBody ;
89import org .springframework .web .bind .annotation .GetMapping ;
910import 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
1218public 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