官术网_书友最值得收藏!

updateUser – implementation in the handler and repository

Here, we will define and implement the updateUser method in our repository. Also, we will call the updateUser method in the main class through UserHandler.

We will add an abstract method for the updateUser method in the UserRepository class:

Mono<Void> updateUser(Mono<User> userMono);

In the UserRepositorySample class, we will add the logic to update the code. Here, we will use the userid as the key and the User object as the value to store in our map:

@;Override
public Mono<Void> updateUser(Mono<User> userMono) {
return userMono.doOnNext(user -> {
users.put(user.getUserid(), user);
System.out.format("Saved %s with id %d%n", user, user.getUserid());
}).thenEmpty(Mono.empty());
}

In the preceding code, we have updated the user by adding the specified user (from the request). Once the user is added in the list, the method will return Mono<Void>; otherwise, it will return the Mono.empty object. 

As we have added the updateUser method in the repository, here we will follow up on our handler:

public Mono<ServerResponse> updateUser(ServerRequest request) {
Mono<User> user = request.bodyToMono(User.class);
return ServerResponse.ok().build(this.userRepository.saveUser(user));
}

In the preceding code, we have converting the user request to Mono<User> by calling the bodyToMono method. The bodyToMono method will extract the body into a Mono object, so it can be used for the saving option.

As we did with other API paths, we add the updateUser API in Server.java:

public RouterFunction<ServerResponse> routingFunction() {
UserRepository repository = new UserRepositorySample();
UserHandler handler = new UserHandler(repository);
return nest (
path("/user"),
nest(
accept(MediaType.ALL),
route(GET("/"), handler::getAllUsers)
)
.andRoute(GET("/{id}"), handler::getUser)
.andRoute(POST("/").and(contentType(APPLICATION_JSON)), handler::createUser)
.andRoute(PUT("/").and(contentType(APPLICATION_JSON)), handler::updateUser)
);
}
主站蜘蛛池模板: 措勤县| 民和| 桃园县| 北辰区| 卢氏县| 元阳县| 文安县| 十堰市| 布尔津县| 长顺县| 阿巴嘎旗| 华亭县| 卢龙县| 喀喇| 大厂| 荥经县| 赞皇县| 航空| 祁门县| 东山县| 运城市| 湾仔区| 江孜县| 巫溪县| 都匀市| 三穗县| 七台河市| 鄂托克前旗| 嘉鱼县| 永修县| 兰州市| 陕西省| 灵山县| 界首市| 府谷县| 栖霞市| 福海县| 卫辉市| 隆德县| 扬州市| 大渡口区|