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

getUser – implementation in the handler and repository

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

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

Mono<User> getUser(Integer id);

Here, we will add the code for the getUser method. You can see that we have used the Mono return type for single-resource access.

In the UserRepositorySample class (the concrete class for UserRepository), we will implement the abstract method getUser:

@Override
public Mono<User> getUser(Integer id){
return Mono.justOrEmpty(this.users.get(id));
}

In the preceding code, we have retrieved the specific user by id. Also, we have mentioned that if the user is not available, the method should be asked to return an empty Mono.

In the UserHandler method, we will talk about how to handle the request and apply our business logic to get the response:

public Mono<ServerResponse> getUser(ServerRequest request){
int userId = Integer.valueOf(request.pathVariable("id"));
Mono<ServerResponse> notFound = ServerResponse.notFound().build();
Mono<User> userMono = this.userRepository.getUser(userId);
return userMono
.flatMap(user -> ServerResponse.ok().contentType(APPLICATION_JSON).body(fromObject(user)))
.switchIfEmpty(notFound);
}

In the preceding code, we have just converted the string id to an integer in order to supply it to our Repository method (getUser). Once we receive the result from the Repository, we are just mapping it in to Mono<ServerResponse> with the JSON content type. Also, we use switchIfEmpty to send the proper response if no item is available. If the searching item is not available, it will simply return the empty Mono object as a response.

Finally, we will add getUser in our routing path, which is 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)
);
}

In the preceding code, we have just added a new entry, .andRoute(GET("/{id}"), handler::getUser), in our existing routing path. By doing so, we have added the getUser method and the corresponding REST API part to access a single user. After restarting the server, we should be able to use the REST API.

主站蜘蛛池模板: 秦皇岛市| 通辽市| 光泽县| 邵东县| 富宁县| 庐江县| 卓尼县| 东海县| 开江县| 东阳市| 清镇市| 乌海市| 清丰县| 噶尔县| 乌拉特后旗| 敦煌市| 鱼台县| 定西市| 民乐县| 黄浦区| 怀化市| 广东省| 安化县| 会同县| 海南省| 丰顺县| 当阳市| 黑龙江省| 焉耆| 乌拉特前旗| 常州市| 龙江县| 巴林右旗| 吉木萨尔县| 迁西县| 宁强县| 合江县| 青阳县| 浮山县| 聂拉木县| 南乐县|