spring webflux 查询一个日期并更新

spring webflux query one date and update

我有一个 RESTful API 用于通过 id 查询一个数据,并更新 ExpiredTime = ExpiredTime + input day.

由于我在响应式编程方面的经验有限,我的代码看起来很难看。如何改进?

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

你可以这样改写:

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