22// Licensed under the MIT license.
33
44using System . Linq ;
5+ using System . Text . RegularExpressions ;
56using Microsoft . OpenApi . Models ;
6- using Microsoft . OpenApi . Properties ;
77
88namespace Microsoft . OpenApi . Validations . Rules
99{
@@ -14,16 +14,46 @@ namespace Microsoft.OpenApi.Validations.Rules
1414 public static class OpenApiResponsesRules
1515 {
1616 /// <summary>
17- /// An OpenAPI operation must contain at least one successful response
17+ /// An OpenAPI operation must contain at least one response
1818 /// </summary>
19- public static ValidationRule < OpenApiResponses > ResponsesMustContainSuccessResponse =>
19+ public static ValidationRule < OpenApiResponses > ResponsesMustContainAtLeastOneResponse =>
2020 new ValidationRule < OpenApiResponses > (
21- ( context , item ) =>
21+ ( context , responses ) =>
2222 {
23- if ( ! item . Keys . Any ( k => k . StartsWith ( "2" ) ) ) {
24- context . AddError ( new ValidationError ( ErrorReason . Required , context . PathString , "Responses must contain success response" ) ) ;
23+ if ( ! responses . Keys . Any ( ) )
24+ {
25+ context . AddError (
26+ new ValidationError (
27+ ErrorReason . Required ,
28+ context . PathString ,
29+ "Responses must contain at least one response" ) ) ;
2530 }
2631 } ) ;
2732
33+ /// <summary>
34+ /// The response key must either be "default" or an HTTP status code (1xx, 2xx, 3xx, 4xx, 5xx)
35+ /// </summary>
36+ public static ValidationRule < OpenApiResponses > ResponsesMustBeIdentifiedByDefaultOrStatusCode =>
37+ new ValidationRule < OpenApiResponses > (
38+ ( context , responses ) =>
39+ {
40+ foreach ( var key in responses . Keys )
41+ {
42+ context . Enter ( key ) ;
43+
44+ if ( key != "default" && ! Regex . IsMatch ( key , "^[1-5]([0-9][0-9]|XX)$" ) )
45+ {
46+ context . AddError (
47+ new ValidationError (
48+ ErrorReason . Format ,
49+ context . PathString ,
50+ "Responses key must be 'default', an HTTP status code, " +
51+ "or one of the following strings representing a range of HTTP status codes: " +
52+ "'1XX', '2XX', '3XX', '4XX', '5XX'" ) ) ;
53+ }
54+
55+ context . Exit ( ) ;
56+ }
57+ } ) ;
2858 }
2959}
0 commit comments