kotlin - avoid passing redundant parameters
问题描述
I am using Kotlin with Spring Webflux.
I have two functions which extract the some data from the request, makes the extracted data available to the upcoming function.
The example contains only two functions but I have a dozen.
suspend fun extractQueryParam1(serverRequest: ServerRequest,
fn: (p1: String) -> ServerResponse): ServerResponse =
serverRequest.queryParamOrNull("p1")
?.let(fn)
?: badRequestResponse("Missing p1")
suspend fun extractQueryParam2(serverRequest: ServerRequest,
fn: (p1: Long) -> ServerResponse): ServerResponse =
serverRequest.queryParamOrNull("p2")
?.toLong()
?.let(fn)
?: badRequestResponse("Missing p2")
Usage
extractQueryParam1(req) { p1 ->
extractQueryParam2(req) { p2 ->
}
}
The req
is somehow like a context for these functions and they share the same context.
What I would like to achieve is somehow to avoid passing the req
manually.
Is this achievable in Kotlin? How?
I inspired myself from Akka HTTP in terms of usage. They achieved this using Directives but I haven't go there... yet.
Here is an example: https://doc.akka.io/docs/akka-http/current/routing-dsl/routes.html#route-seal-method-to-modify-httpresponse
解决方案
Make them into extension functions, and then you can use with
or run
scopes to call a series of these without repeatedly passing the parameter.
suspend fun ServerRequest.extractQueryParam1(
fn: (p1: String) -> ServerResponse): ServerResponse =
queryParamOrNull("p1")
?.let(fn)
?: badRequestResponse("Missing p1")
suspend fun ServerRequest.extractQueryParam2(
fn: (p1: Long) -> ServerResponse): ServerResponse =
queryParamOrNull("p2")
?.toLong()
?.let(fn)
?: badRequestResponse("Missing p2")
Usage:
with(req) {
extractQueryParam1 { p1 ->
extractQueryParam2 { p2 ->
}
}
}
Since you're building a DSL, instead of with
or run
, you might want to write your own scope function that builds the request and then runs the code within its lambda, using the build request as the receiver.
推荐阅读
- regex - 正则表达式仅获取单词 {word} 单词 {word} 单词的序列,但不是两个相似的接近
- postgresql - Postgres:从 JSON 数组创建 JSON 对象并添加键
- modelmapper - 为什么我不能将 modelMapper 映射到 Commercetools 类?
- javascript - 用 JS HTML 扩展文件
- angular - Angular 生产版本存在 useHash 问题
- python - 网页抓取/抓取 Google Play 商店/iTunes
- mysql - 使用 MySQL 查询创建 WordPress 用户
- python - 写入小数精度 0 但包括小数点
- php - Laravel 5.7 ModelNotFoundException 不为 API 调用返回 json
- java - Jackson 转换器应抛出什么异常类型以指示无效值