Sulaiman Fahmi
Sulaiman Fahmi

Reputation: 17

Webflux data check with mongo reactive spring

I try to learn Webflux, but im facing problem when i want to validate list id of employee before save the data. And my qestion How to catch error, when employeId is doesn't exist and show the error to client?

    @PostMapping(path = "/{tenantId}/outlet")
public Mono<OutletEntity> createNewOutlet(@PathVariable String tenantId, @RequestBody OutletEntity outletEntity) {
    return Mono.just(outletEntity).map(outletEntity1 -> {
        outletEntity.getEmployees().forEach(s -> {
            this.employeeService.getRepository().existsById(s).subscribe(aBoolean -> {
                System.out.println(aBoolean);
                if (!aBoolean) {
                    /**
                     * variable s is employeId
                     * i want to validate every single  employee id before save new outlet
                     */
                    throw new ApiExceptionUtils("tenant not found", HttpStatus.UNPROCESSABLE_ENTITY.value(),
                            StatusCodeUtils.TENANT_NOT_FOUND);
                }
            });
        });
        return outletEntity1;
    }).flatMap(outletEntity1 -> {
        outletEntity.setTenantId(tenantId);
        return  this.outletRepository.save(outletEntity);
    });

Upvotes: 1

Views: 1997

Answers (1)

Yauhen Balykin
Yauhen Balykin

Reputation: 771

Better way run your validation in the same chain without additional subscriber

return Flux.fromIterable(outletEntity.getEmployees()) (1)
        .flatMap(this.employeeService.getRepository()::existsById)
        .doOnNext(System.out::println)
        .map(aBoolean -> {
            if (!aBoolean) { (2)
                throw new ApiExceptionUtils("tenant not found", HttpStatus.UNPROCESSABLE_ENTITY.value(),
                    StatusCodeUtils.TENANT_NOT_FOUND);
            }
            else {
                return aBoolean;
            }
        })
        .then(Mono.just(outletEntity)) (3)
        .flatMap(outletEntity1 -> {
            outletEntity.setTenantId(tenantId);
            return  this.outletRepository.save(outletEntity);
        });

1) Create Flux from employees collection and iterate via reactor streams with a validation;

2) Check if your type false and throw exception, it stops this chain;

3) If everything ran smoothly then() switch to Mono with the outletEntity, saves it and returns;

About error handling. If you don't handle errors, WebFlux resolve it in DefaultErrorWebExceptionHandler.

You can add your own error handling like in Web MVC or add you custom exception handler in the WebFlux Config.

More details you can read here: web-reactive

Upvotes: 2

Related Questions