Skip to content

Commit 89ccb3a

Browse files
committed
Add validation methods for request and response
1 parent 625cc37 commit 89ccb3a

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

router-openapi-request-validator/src/main/kotlin/com/github/mduesterhoeft/router/openapi/OpenApiValidator.kt

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,24 @@ class OpenApiValidator(val specUrlOrPayload: String) {
2222
return validate(request, response).let { if (it.hasErrors()) throw ApiInteractionInvalid(specUrlOrPayload, request, response, it) }
2323
}
2424

25-
class ApiInteractionInvalid(val spec: String, val request: APIGatewayProxyRequestEvent, val response: APIGatewayProxyResponseEvent, val validationReport: ValidationReport) :
25+
fun assertValidRequest(request: APIGatewayProxyRequestEvent) =
26+
validator.validateRequest(request.toRequest()).let { if (it.hasErrors()) throw ApiInteractionInvalid(
27+
spec = specUrlOrPayload,
28+
request = request,
29+
validationReport = it) }
30+
31+
fun assertValidResponse(request: APIGatewayProxyRequestEvent, response: APIGatewayProxyResponseEvent) =
32+
request.toRequest().let { r ->
33+
validator.validateResponse(r.path, r.method, response.toResponse()).let {
34+
if (it.hasErrors()) throw ApiInteractionInvalid(
35+
spec = specUrlOrPayload,
36+
request = request,
37+
validationReport = it
38+
)
39+
}
40+
}
41+
42+
class ApiInteractionInvalid(val spec: String, val request: APIGatewayProxyRequestEvent, val response: APIGatewayProxyResponseEvent? = null, val validationReport: ValidationReport) :
2643
RuntimeException("Error validating request and response against $spec - $validationReport")
2744

2845
private fun APIGatewayProxyRequestEvent.toRequest(): Request {

router-openapi-request-validator/src/test/kotlin/com/github/mduesterhoeft/router/openapi/OpenApiValidatorTest.kt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ class OpenApiValidatorTest {
2222

2323
val response = testHandler.handleRequest(request, mockk())
2424

25+
validator.assertValidRequest(request)
26+
validator.assertValidResponse(request, response)
2527
validator.assertValid(request, response)
2628
}
2729

@@ -33,6 +35,7 @@ class OpenApiValidatorTest {
3335
val response = testHandler.handleRequest(request, mockk())
3436

3537
thenThrownBy { validator.assertValid(request, response) }.isInstanceOf(OpenApiValidator.ApiInteractionInvalid::class.java)
38+
thenThrownBy { validator.assertValidRequest(request) }.isInstanceOf(OpenApiValidator.ApiInteractionInvalid::class.java)
3639
}
3740

3841
@Test

0 commit comments

Comments
 (0)