Skip to content

Instantly share code, notes, and snippets.

@massenz
Last active August 25, 2021 17:25
Show Gist options
  • Save massenz/bafaffa478d578b7a869343d344ea7e6 to your computer and use it in GitHub Desktop.
Save massenz/bafaffa478d578b7a869343d344ea7e6 to your computer and use it in GitHub Desktop.
OpenAPI Codex-generated Rest Controller for Spring Data
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
@Autowired
private UserMapper user
/**
* CreateUser creates a new User and inserts it into our database, using
* Spring Data for Mongo.
*/
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User createdUser = userRepository.save(user);
return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
}
/**
* GetUser retrieves a User from our database using Spring Data for Mongo.
*/
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable String id) {
User user = userRepository.findById(id).orElse(null);
if (user == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(user, HttpStatus.OK);
}
/**
* UpdateUser updates a User in our database using Spring Data for Mongo.
*/
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable String id, @RequestBody User user) {
User updatedUser = userRepository.findById(id).orElse(null);
if (updatedUser == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
updatedUser.setFirstName(user.getFirstName());
updatedUser.setLastName(user.getLastName());
updatedUser.setEmail(user.getEmail());
updatedUser.setPassword(user.getPassword());
updatedUser.setRole(user.getRole());
updatedUser.setEnabled(user.isEnabled());
updatedUser.setLastPasswordResetDate(user.getLastPasswordResetDate());
// We save the updated User to the repository, and return it to the caller.
User updated = userRepository.save(updatedUser);
return new ResponseEntity<>(updated, HttpStatus.OK);
}
/**
* DeleteUser deletes a User from our database using Spring Data for Mongo.
*/
@DeleteMapping("/{id}")
public ResponseEntity<User> deleteUser(@PathVariable String id) {
User deletedUser = userRepository.findById(id).orElse(null);
// If the id does not match any user, we return a NotFound response
if (deletedUser == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
// We delete the user from the repository, and return it to the caller.
userRepository.delete(deletedUser);
return new ResponseEntity<>(deletedUser, HttpStatus.OK);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment