Implementing controllers

The following code is for TweetController, which caters for retrieving and saving tweets:

@RestController
@RequestMapping("/tweets")
public class TweetController {

private final TweetService tweetService;
private final UserService userService;

public TweetController(TweetService tweetService, UserService
userService) {
this.tweetService = tweetService;
this.userService = userService;
}

@PostMapping
public Mono<Tweet> save(Principal principal, @RequestBody Tweet
tweet) {
Mono<User> user =
userService.getUserByScreenName(principal.getName());
return user.flatMap(u -> {
tweet.setTweetUser(u);
return tweetService.save(tweet);
});
}

@GetMapping
public Flux<Tweet> getAll(Principal principal) {
return tweetService.getRelevantTweets(principal.getName());
}

}

From the preceding code, we can see that the save method uses Principal, which has information about the logged in user, to save a Tweet object sent as the request body of a POST method.

The getAll method uses Principal, which has information about the logged in user, to retrieve all the tweets relevant to that user.

The following code is for UserControllerwhich caters for retrieving the user by screenName and following a user by user ID:

@RestController
@RequestMapping("/users")
public class UserController {

private final UserService userService;

public UserController(UserService userService) {
this.userService = userService;
}

@GetMapping("/{screenName}")
public Mono<User> getUserByScreenName(@PathVariable String
screenName) {
return userService.getUserByScreenName(screenName);
}

@PutMapping("/{userId}/follow")
@ResponseStatus(code = HttpStatus.OK)
public void followUser(Principal principal, @PathVariable String
userId) {
Mono<User> user =
userService.getUserByScreenName(principal.getName());
user.subscribe(u -> {
if (!u.getUserId().equalsIgnoreCase(userId)) {
u.getFollowing().add(userId);
userService.save(u);
}
});
}
}

The getUserByScreenName method will use screenName sent as part of the URL to retrieve the matching user. 

The followUser method will use the Principal object and the user ID submitted as part of the URL to follow a user. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.211.239