当前位置: 首页 > 知识库问答 >
问题:

Spring WebFlux:Reactive MongoDB

郗俊能
2023-03-14
fun save(user: User): Mono<User> {
    if (findByEmail(user.email).block() != null) {
        throw UserAlreadyExistsException()
    }

    user.password = passwordEncoder.encode(user.password)
    return userRepository.save(user)
}

谢谢

共有1个答案

应和悦
2023-03-14

像这样的事情应该会奏效:

  open fun save(req: ServerRequest): Mono<ServerResponse> {
    logger.info { "${req.method()} ${req.path()}" }
    return req.bodyToMono<User>().flatMap {
      // You might need to "work out" this if since I don't know what you are doing
      if (null != findByEmail(it.email).block()) {
        throw UserAlreadyExistsException()
      }
      it.password = passwordEncoder.encode(it.password)
      repository.save(it).flatMap {
        logger.debug { "Entity saved successfully! Result: $it" }
        ServerResponse.created(URI.create("${req.path()}/${it.id}")).build()
      }
    }
  }

注意,我使用的是microutils/kotlin-logging。如果您不知道或只是不想要日志语句,请删除它们。

基本上,您需要首先“消费”(也称为订阅)ServerRequest中的内容,以便访问内容。

open fun ...
  return ServerResponse.ok()
      // Keep doing stuff here...if something is wrong
      .switchIfEmpty(ServerResponse.notFound().build())
}
 类似资料:

相关问答

相关文章

相关阅读