- Building RESTful Web Services with Spring 5(Second Edition)
- Raja CSP Raman Ludovic Dewailly
- 268字
- 2021-06-30 19:13:31
createUser – implementation in the handler and repository
Here, we will define and implement the createUser method in our repository. Also, we will call the createUser method in the main class through UserHandler.
We will add an abstract method for the createUser method in the UserRepository class:
Mono<Void> saveUser(Mono<User> userMono);
Here, we will talk about how to save the user by using the sample repository method.
In UserRepositorySample (the concrete class for UserRepository), we will implement the abstract method createUser:
@Override
public Mono<Void> saveUser(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 used doOnNext to save the user on the repository. Also, the method will return the empty Mono in the case of failure.
As we have added the createUser method in the repository, here we will follow up on our handler:
public Mono<ServerResponse> createUser(ServerRequest request) {
Mono<User> user = request.bodyToMono(User.class);
return ServerResponse.ok().build(this.userRepository.saveUser(user));
}
In the UserHandler class, we have created the createUser method to add a user through a handler. In the method, we extract the request into Mono by the bodyToMono method. Once the user is created, it will be forwarded to UserRepository to save the method.
Finally, we will add the REST API path to save the user in our existing routing function 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)
);
}
- 解析QUIC/HTTP3:未來互聯(lián)網(wǎng)的基石
- 異構(gòu)基因共表達(dá)網(wǎng)絡(luò)的分析方法
- HTML5 Game development with ImpactJS
- 物聯(lián)網(wǎng)長距離無線通信技術(shù)應(yīng)用與開發(fā)
- 通信原理及MATLAB/Simulink仿真
- Building Web Applications with ArcGIS
- TD-LTE無線網(wǎng)絡(luò)規(guī)劃與設(shè)計
- 網(wǎng)絡(luò)設(shè)計與應(yīng)用(第2版)
- Getting Started with Memcached
- AIoT應(yīng)用開發(fā)與實踐
- 深入理解Nginx:模塊開發(fā)與架構(gòu)解析
- 組網(wǎng)技術(shù)與網(wǎng)絡(luò)管理
- Dart Cookbook
- Guide to NoSQL with Azure Cosmos DB
- Enterprise ApplicationDevelopment with Ext JSand Spring