io.specmatic.conversions.ExampleRequestBuilder.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of specmatic-core Show documentation
Show all versions of specmatic-core Show documentation
Turn your contracts into executable specifications. Contract Driven Development - Collaboratively Design & Independently Deploy MicroServices & MicroFrontends.
package io.specmatic.conversions
import io.specmatic.core.HttpPathPattern
import io.specmatic.core.HttpRequest
import io.specmatic.core.pattern.parsedValue
class ExampleRequestBuilder(
examplePathParams: Map>,
exampleHeaderParams: Map>,
exampleQueryParams: Map>,
val httpPathPattern: HttpPathPattern,
private val httpMethod: String,
val securitySchemes: Map
) {
fun examplesWithRequestBodies(exampleBodies: Map): Map> {
val examplesWithBodies: Map> = exampleBodies.mapValues { (exampleName, bodyValue) ->
val bodies: List = if(exampleName in examplesBasedOnParameters) {
examplesBasedOnParameters.getValue(exampleName).map { exampleRequest ->
exampleRequest.copy(body = parsedValue(bodyValue))
}
} else {
val httpRequest = HttpRequest(
method = httpMethod,
path = httpPathPattern.path,
body = parsedValue(bodyValue)
)
val requestsWithSecurityParams = securitySchemes.map { (_, securityScheme) ->
securityScheme.addTo(httpRequest)
}
requestsWithSecurityParams
}
bodies
}
val examplesWithoutBodies = (examplesBasedOnParameters.keys - exampleBodies.keys).associate { key ->
key to examplesBasedOnParameters.getValue(key)
}
val allExamples = examplesWithBodies + examplesWithoutBodies
return allExamples
}
private val unionOfParameterKeys =
(exampleQueryParams.keys + examplePathParams.keys + exampleHeaderParams.keys).distinct()
val examplesBasedOnParameters: Map> = unionOfParameterKeys.associateWith { exampleName ->
val queryParams = exampleQueryParams[exampleName] ?: emptyMap()
val pathParams = examplePathParams[exampleName] ?: emptyMap()
val headerParams = exampleHeaderParams[exampleName] ?: emptyMap()
val path = toConcretePath(pathParams, httpPathPattern)
val httpRequest =
HttpRequest(method = httpMethod, path = path, queryParametersMap = queryParams, headers = headerParams)
val requestsWithSecurityParams: List = securitySchemes.map { (_, securityScheme) ->
securityScheme.addTo(httpRequest)
}
requestsWithSecurityParams
}
}
private fun toConcretePath(
pathParams: Map,
httpPathPattern: HttpPathPattern
): String {
val path = pathParams.entries.fold(httpPathPattern.toOpenApiPath()) { acc, (key, value) ->
acc.replace("{$key}", value)
}
return path
}