Reputation: 2101
I try to implement a reactive endpoint to save new entity instances:
Method save in SubjectRepository
is still required Subject
without Mono
wrapper. But how to extract value from the reactive wrapper doesn't clear.
Should I extract Subject
from Mono<Subject>
with request.body(BodyExtractor)
and call SubjectRepository.save(Subject s)
? Or I can somehow save Mono<>
directly to MongoDB?
That is the right way to work with the input body?
Entity:
@Document
public record Subject(@Id UUID id, String route) {}
@Repository
public interface SubjectRepository extends ReactiveMongoRepository<Subject, UUID> {
}
Handler method:
@NotNull
public Mono<ServerResponse> createSubject(@NotNull ServerRequest request) {
Mono<Subject> data = subjectRepository
.save(/** Somehow extract Subject from request */);
return ServerResponse
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(data, Subject.class);
}
Upvotes: 0
Views: 2002
Reputation: 5982
You need to construct the flow using reactive operators that will be executed when web flux subscribes to this flow. In this case use request.bodyToMono
to resolve request body and the continue the sequence to construct ServerResponse
public Mono<ServerResponse> createSubject(ServerRequest request) {
return request.bodyToMono(Subject.class)
.flatMap(subject -> subjectRepository.save(subject))
.flatMap(newSubject ->
ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(newSubject)
);
}
Upvotes: 2