From 4ad47d048d429f198c0781ab77e6a8022687852a Mon Sep 17 00:00:00 2001 From: andacata <1506402+andacata@users.noreply.github.com> Date: Mon, 22 Jul 2024 12:45:43 +0200 Subject: [PATCH] fix(common) #120: Include Message Routing Headers in error responses. --- .../ocpi/toolkit/common/OcpiResponseBody.kt | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/ocpi-toolkit-2.2.1/src/main/kotlin/com/izivia/ocpi/toolkit/common/OcpiResponseBody.kt b/ocpi-toolkit-2.2.1/src/main/kotlin/com/izivia/ocpi/toolkit/common/OcpiResponseBody.kt index 26eaa54..0431371 100644 --- a/ocpi-toolkit-2.2.1/src/main/kotlin/com/izivia/ocpi/toolkit/common/OcpiResponseBody.kt +++ b/ocpi-toolkit-2.2.1/src/main/kotlin/com/izivia/ocpi/toolkit/common/OcpiResponseBody.kt @@ -112,8 +112,14 @@ fun OcpiException.toHttpResponse(): HttpResponse = * @return the HttpResponse properly formatted according to the body generated by fn() */ @Suppress("UNCHECKED_CAST") -suspend fun HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody): HttpResponse = - try { +suspend fun HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody): HttpResponse { + var baseHeaders = mapOf(Header.CONTENT_TYPE to ContentType.APPLICATION_JSON) + + return try { + baseHeaders = baseHeaders + .plus(getDebugHeaders()) + .plus(currentResponseMessageRoutingHeadersOrNull()?.httpHeaders().orEmpty()) + val ocpiResponseBody = fn() val isPaginated = ocpiResponseBody.data is SearchResult<*> @@ -125,6 +131,7 @@ suspend fun HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody): } else { HttpStatus.NOT_FOUND } + OcpiStatus.CLIENT_INVALID_PARAMETERS.code -> HttpStatus.BAD_REQUEST else -> HttpStatus.OK }, @@ -140,9 +147,7 @@ suspend fun HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody): ocpiResponseBody } ), - headers = getDebugHeaders() - .plus(Header.CONTENT_TYPE to ContentType.APPLICATION_JSON) - .plus(currentResponseMessageRoutingHeadersOrNull()?.httpHeaders().orEmpty()) + headers = baseHeaders ).let { if (isPaginated) { it.copy( @@ -155,17 +160,18 @@ suspend fun HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody): } } catch (e: OcpiException) { e.toHttpResponse() - .let { it.copy(headers = it.headers + getDebugHeaders()) } + .let { it.copy(headers = baseHeaders.plus(it.headers)) } } catch (e: HttpException) { logger.error(e) HttpResponse( status = e.status, - headers = getDebugHeaders() + headers = baseHeaders ) } catch (e: JsonProcessingException) { logger.error(e) HttpResponse( status = HttpStatus.BAD_REQUEST, - headers = getDebugHeaders() + headers = baseHeaders ) } +}