Home > Mobile >  spring webflux query one date and update
spring webflux query one date and update

Time:10-19

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())
                    );
            
        }

CodePudding user response:

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()));
  }
  • Related