Search code examples
springreactive-programmingspring-webfluxproject-reactorspring-data-r2dbc

spring webflux query one date and update


I have a RESTful API for Query one data by id , and update ExpiredTime = ExpiredTime + input day.

With my limited experience with Reactive Programing, my code looks ugly. How to improve it?

   @Autowired
    R2dbcEntityTemplate r2dbcEntityTemplate;
     /**
         *
         * @param vo   json with {tenantId:"",day:"1"}
         * @return 404 OR 2XX
         */
        @PatchMapping
        public Mono<ResponseEntity<Void>> updateTime(@RequestBody TenantUpdate vo) {
            return r2dbcEntityTemplate
                    .selectOne(query(where("tenant_id").is(vo.getTenantId())), Tenant.class)
                    .flatMap((Function<Tenant, Mono<Tenant>>) db -> {
    
                       if ( db.getTenantExpiredTime()==null){
                           db.setTenantExpiredTime(LocalDateTime.now());
                       }
                        db.setTenantExpiredTime(db.getTenantExpiredTime().plusDays(vo.getDay()));
                        return Mono.just(db);
                    })
                    //todo test ObjectOptimisticLockingFailureException
                    .flatMap(m -> r2dbcEntityTemplate.update(m))
                    .flatMap((Function<Tenant, Mono<? extends ResponseEntity<Void>>>)
                            m -> Mono.just(ResponseEntity.noContent().build()))
    
                    .switchIfEmpty(Mono.just(ResponseEntity
                            .notFound()
                            .build())
                    );
            
        }

Solution

  • You could rewrite it like this:

      @PatchMapping
      public Mono<ResponseEntity<Void>> updateTime(@RequestBody TenantUpdate request) {
        return r2dbcTemplate.selectOne(query(where("tenant_id").is(request.getTenantId())), Tenant.class)
            .map(t -> {
              t.setTenantExpiredTime(t.getTenantExpiredTime() == null ? LocalDateTime.now() : t.getTenantExpiredTime().plusDays(request.getDay()));
              return t;
            })
            //todo test ObjectOptimisticLockingFailureException
            .flatMap(t -> r2dbcTemplate.update(t))
            .map(t -> new ResponseEntity<Void>(HttpStatus.NO_CONTENT))
            .switchIfEmpty(Mono.just(ResponseEntity.notFound().build()));
      }