Skip to content

Instantly share code, notes, and snippets.

@wkorando
Last active April 6, 2020 18:37
Show Gist options
  • Save wkorando/fd4bd90ddd2c1b1cb580b5da2c0e2250 to your computer and use it in GitHub Desktop.
Save wkorando/fd4bd90ddd2c1b1cb580b5da2c0e2250 to your computer and use it in GitHub Desktop.
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
private UserService service;
public UserController(UserService service) {
this.service = service;
}
@GetMapping
public List<User> findAll() {
return service.findAll();
}
@GetMapping("/{userId}")
public User findUser(@PathVariable long userId) {
return service.findUser(userId);
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User createdUser = service.createUser(user);
return ResponseEntity.created(URI.create(String.format("/api/v1/users/%d", createdUser.getId())))
.body(createdUser);
}
@PutMapping("/{userId}")
public User updateUser(@PathVariable long userId, @RequestBody User user) {
return service.updateUser(userId, user);
}
@DeleteMapping("/{userId}")
public ResponseEntity<Void> deleteUser(@PathVariable long userId) {
service.deleteUser(userId);
return ResponseEntity.ok().build();
}
@ExceptionHandler(ClientException.class)
public ResponseEntity<String> clientError(ClientException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<String> resourceNotFound(NotFoundException e) {
return ResponseEntity.notFound().build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment