2017-08-30 39 views
0

我是新來春堆,所以我想重構這個簡單的彈簧數據(在科特林)方法:春WebFlux:無MongoDB的

fun save(user: User): Mono<User> { 
    if (findByEmail(user.email).block() != null) { 
     throw UserAlreadyExistsException() 
    } 

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

感謝

+0

你應該解釋一下你的問題是什麼 – s1m0nw1

+0

@ s1m0nw1我想反應的風格重構這個 – maystrovyy

回答

0

像這樣的東西應該工作:

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

您可以調整例如你User類型的情況下,你真的想代替它傳遞一個ServerRequest的。

0

(原諒我,如果在科特林語法是錯誤的,如果我做在Java中風格的東西:O)

fun save(user: User): Mono<User> { 
    //we'll prepare several helpful Monos and finally combine them. 
    //as long as we don't subscribe to them, nothing happens. 

    //first we want to short-circuit if the user is found (by email). 
    //the mono below will onError in that case, or be empty 
    Mono<User> failExistingUser = findByEmail(user.email) 
     .map(u -> { throw new UserAlreadyExistsException(); }); 

    //later we'll need to encode the password. This is likely to be 
    //a blocking call that takes some time, so we isolate that call 
    //in a Mono that executes on the Elastic Scheduler. Note this 
    //does not execute immediately, since it's not subscribed to yet... 
    Mono<String> encodedPassword = Mono 
     .fromCallable(() -> passwordEncoder.encode(user.password)) 
     .subscribeOn(Schedulers.elastic()); 

    //lastly the save part. We want to combine the original User with 
    //the result of the encoded password. 
    Mono<User> saveUser = user.toMono() //this is a Kotlin extension 
     .and(encodedPassword, (u, p) -> { 
      u.password = p; 
      return u; 
     }) 
     //Once this is done and the user has been updated, save it 
     .flatMap(updatedUser -> userRepository.save(updatedUser)); 

    //saveUser above is now a Mono that represents the completion of 
    //password encoding, user update and DB save. 

    //what we return is a combination of our first and last Monos. 
    //when something subscribes to this combination: 
    // - if the user is found, the combination errors 
    // - otherwise, it subscribes to saveUser, which triggers the rest of the process 
    return failExistingUser.switchIfEmpty(saveUser); 
} 

縮短的版本,而中介變量,也不評論:

fun save(user: User): Mono<User> { 
    return findByEmail(u.email) 
     .map(u -> { throw new UserAlreadyExistsException(); }) 
     .switchIfEmpty(user.toMono()) 
     .and(Mono.fromCallable(() -> passwordEncoder.encode(user.password)) 
       .subscribeOn(Schedulers.elastic()), 
      (u, p) -> { 
       u.password = p; 
       return u; 
      }) 
     .flatMap(updatedUser -> userRepository.save(updatedUser)); 
} 
0

您可以在單聲道中使用hasElement()功能。在這個擴展功能看看到單聲道:

inline fun <T> Mono<T>.errorIfEmpty(crossinline onError:() -> Throwable): Mono<T> { 
     return this.hasElement() 
       .flatMap { if (it) this else Mono.error(onError()) } 
} 

inline fun <T> Mono<T>.errorIfNotEmpty(crossinline onError: (T) -> Throwable): Mono<T> { 
    return this.hasElement() 
      .flatMap { if (it) Mono.error(onError.invoke(this.block()!!)) else this } 
} 

switchIfEmpty的問題是,它總是評估參數傳遞表達 - 寫這樣的代碼總是會產生Foo對象:

mono.switchIfEmpty(Foo()) 

你可以寫您自己的擴展懶惰評估表達參數傳遞:

inline fun <T> Mono<T>.switchIfEmpty(crossinline default:() -> Mono<T>): Mono<T> { 
    return this.hasElement() 
      .flatMap { if (it) this else default() } 
} 

這裏有兩個以上的擴展功能 - 你可以用它們來檢查wheth呃密碼是正確的:

inline fun <T> Mono<T>.errorIf(crossinline predicate: (T) -> Boolean, crossinline throwable: (T) -> Throwable): Mono<T> { 
    return this.flatMap { if (predicate(it)) Mono.error(throwable(it)) else Mono.just(it) } 
} 

inline fun <T> Mono<T>.errorIfNot(crossinline predicate: (T) -> Boolean, crossinline throwable: (T) -> Throwable): Mono<T> { 
    return this.errorIf(predicate = { !predicate(it) }, throwable = throwable) 
}