在春季启动中如何使用http补丁请求?

时间:2019-06-29 21:20:40

标签: spring-boot spring-webflux

我正在尝试使用PATCH请求。

下面是我正在使用的代码。就像if语句的阶梯

@PatchMapping("/updateInvoiceByEmail/{email}")
    public Mono<ResponseEntity<Invoice>> updateInvoiceByEmail(
                @PathVariable String email,
                @RequestBody Invoice invoice) {

        return invoiceRepository
        .findByEmail(vendorEmail)

        .flatMap(existing -> {
            if (invoice.getInvoiceStatus() != null) {
                existing.setInvoiceStatus(invoice.getInvoiceStatus());
            }
            if (invoice.getCanRaise() != null) {
                existing.setCanRaise(invoice.getCanRaise());
            }
            if (invoice.getAttachmentId() != null) {
                existing.setAttachmentId(invoice.getAttachmentId());
            }
            if (invoice.getInvoiceId() != null) {
                existing.setInvoiceId(invoice.getInvoiceId());
            }
            ... and so on.
            return invoiceRepository.save(existing);

        })
        .map(updatedInvoice -> new ResponseEntity<>(updatedInvoice, HttpStatus.OK))
        .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));

我正在使用 Spring WebFlux和mongodb

我该如何做得更短更清洁。

谢谢

2 个答案:

答案 0 :(得分:0)

如果您想减少行数,则可以使用反射,尽管反射始终是您应该做的最后一件事。我要做的是移动-如果-在单独的组件(在单独的类或方法中)中设置逻辑。除此之外,我只想提到简单性不是这里的唯一问题。假设null是客户端发送的有效值,您将需要某种机制来检测是否未发送值,或者您明确想要设置null的值。将此代码移至单独的组件的一些示例如下所示:

class InvoiceAssembler {
   public static assemble(Invoice existing, Invoice newInvoice) {
     if(newInvoice.getInvoiceId() != null) {
         existing.setInvoiceId(newInvoice.getInvoiceId());
     }
     ...
   }
} 

答案 1 :(得分:0)

我认为可以改善的唯一方法是,如果对最有可能更新的字段使用UpdateDTO,从而减少了必须检查的字段数量。

Good description of how you use UpdateDTO here

否则,您将不得不进行反思,但是我不知道这是否会使您的代码更易读或更令人困惑。

相关问题