Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additional BiDiBodyLens functions? #923

Open
jhult opened this issue Jun 15, 2023 · 0 comments
Open

Additional BiDiBodyLens functions? #923

jhult opened this issue Jun 15, 2023 · 0 comments

Comments

@jhult
Copy link
Contributor

jhult commented Jun 15, 2023

Would the following functions be helpful to add to http4k-core? If so, I can submit a PR. If not, I can keep them as extension functions. However, it seems like they might be useful to others (perhaps with some changes to the Exceptions that are thrown, such as using IllegalArgumentException or IllegalStateException).

/**
 * Throws an [InvalidInputException] if the [response][Response] [status][Status] is
 * [400][Status.BAD_REQUEST]. Otherwise, apply the [BiDiBodyLens] to the [response][Response].
 *
 * @see validate
 */
@Throws(InvalidInputException::class)
fun <FINAL> BiDiBodyLens<FINAL>.getOrThrow(response: Response): FINAL {
    if (response.status == Status.BAD_REQUEST) throw InvalidInputException(response.body.toString())
    response.validate()
    return this(response)
}

/**
 * If the [response][Response] is [204][Status.NO_CONTENT], return `null`. Otherwise, apply the
 * [BiDiBodyLens] to the [response][Response].
 *
 * @see validate
 */
fun <FINAL> BiDiBodyLens<FINAL>.optional(response: Response): FINAL? {
    response.validate()
    return if (response.status == Status.NO_CONTENT) null else this(response)
}

/**
 * If the [response][Response] is [204][Status.NO_CONTENT], return an empty [List][emptyList].
 * Otherwise, apply the [BiDiBodyLens] to the [response][Response].
 *
 * @see validate
 */
fun <FINAL> BiDiBodyLens<List<FINAL>>.optional(response: Response): List<FINAL> {
    response.validate()
    return if (response.status == Status.NO_CONTENT) emptyList() else this(response)
}

/**
 * Throws a [ResponseException] if the [Response] [status][Status] is not [200][Status.OK] or
 * [204][Status.NO_CONTENT].
 */
@Throws(ResponseException::class)
fun Response.validate() {
    if (status !in listOf(Status.OK, Status.NO_CONTENT)) throw ResponseException(status)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant