【问题标题】:How to buld a rest ful API with RXJava and Micronaut?如何使用 RXJava 和 Micronaut 构建一个宁静的 API?
【发布时间】:2019-09-17 09:29:24
【问题描述】:

我想编写一个 REST API,当我尝试创建已存在的实体或尝试更新不存在的实体时返回 HTTP 400。

@Post
fun create(@Body entity: @Valid Entity): HttpResponse<Entity> {
    val optional = entityService.find(entity)
    if(optional.isPresent) {
        return HttpResponse.badRequest()
    }
    return HttpResponse.created(entityService.save(entity))
}

如何使用带有 RXJava2 和 Micronaut 的非阻塞端点来做到这一点,我只能找到带有 switchIfEmpty

的示例
@Post
@Status(HttpStatus.CREATED)
fun createMeal(@Body entity: @Valid Entity): Single<Entity> {
    return entityService.find(entity)
            .switchIfEmpty(entityService.save(entity))
            .map{success -> entity}
}

但即使没有保存任何内容,此代码也总是返回 HTTP 200,我认为这不是一个好习惯。

谢谢

【问题讨论】:

    标签: rest rx-java2 micronaut


    【解决方案1】:

    您将使用map 将实体转换为错误的请求响应,因为如果它存在,那就是您想要返回的内容。您还可以使用 switchIfEmpty 来保存仅在找不到实体时才会出现的实体。确保将该代码包装在 Flowable.defer 中,以防止无论如何执行逻辑。在上面的反应式示例中,每次执行都会发生保存。

    return entityService.find(entity)
        .map(entity -> HttpResponse.badRequest())
        .switchIfEmpty(Flowable.defer() -> {
            //return a publisher that emits HttpResponse.created(entity)
        })
    

    【讨论】:

    • 我稍后会测试你的解决方案,这次我很短。谢谢
    • 您好,我找到了这种更新方式:entityRepository.find(name) .flatMapSingleElement { entityRepository.update(entity) } .switchIfEmpty(Single.error&lt;Meal&gt; { RuntimeException("Entityl $name do not exists") }) 但没有保存的线索
    【解决方案2】:

    最后我做了这样的事情:

    fun update(name: String, entity: Entity): Single<Entity> {
        val observable = BehaviorSubject.create<Entity>()
        entitysRepository.find(name)
                .subscribe(
                        {
                            entity.name = name
                            update(entity, observable)
                        },
                        { observable.onError(RuntimeException("Entity : $name doesn't exist")) }
                )
        return observable.singleOrError()
    }
    
    fun save(entity: Entity): Single<Entity> {
        val observable = BehaviorSubject.create<Entity>()
        entitysRepository.find(entity.name)
                .subscribe(
                        { observable.onError(RuntimeException("Entity : ${entity.name} already exist")) },
                        { save(entity, observable) }
                )
        return observable.singleOrError()
    }
    

    真的不知道这是否是一个好习惯。

    【讨论】:

      猜你喜欢
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多