-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathOpenApiParameterRules.cs
More file actions
75 lines (71 loc) · 3.09 KB
/
OpenApiParameterRules.cs
File metadata and controls
75 lines (71 loc) · 3.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace Microsoft.OpenApi
{
/// <summary>
/// The validation rules for <see cref="OpenApiParameter"/>.
/// </summary>
[OpenApiRule]
public static class OpenApiParameterRules
{
/// <summary>
/// Validate the field is required.
/// </summary>
public static ValidationRule<IOpenApiParameter> ParameterRequiredFields =>
new(nameof(ParameterRequiredFields),
(context, item) =>
{
// name
if (item.Name == null)
{
context.Enter("name");
context.CreateError(nameof(ParameterRequiredFields),
string.Format(SRResource.Validation_FieldIsRequired, "name", "parameter"));
context.Exit();
}
// in
if (item.In == null)
{
context.Enter("in");
context.CreateError(nameof(ParameterRequiredFields),
string.Format(SRResource.Validation_FieldIsRequired, "in", "parameter"));
context.Exit();
}
});
/// <summary>
/// Validate the "required" field is true when "in" is path.
/// </summary>
public static ValidationRule<IOpenApiParameter> RequiredMustBeTrueWhenInIsPath =>
new(nameof(RequiredMustBeTrueWhenInIsPath),
(context, item) =>
{
// required
if (item.In == ParameterLocation.Path && !item.Required)
{
context.Enter("required");
context.CreateError(
nameof(RequiredMustBeTrueWhenInIsPath),
"\"required\" must be true when parameter location is \"path\"");
context.Exit();
}
});
/// <summary>
/// Validate that a path parameter should always appear in the path
/// </summary>
public static ValidationRule<IOpenApiParameter> PathParameterShouldBeInThePath =>
new(nameof(PathParameterShouldBeInThePath),
(context, parameter) =>
{
if (parameter.In == ParameterLocation.Path &&
!(context.PathString.Contains("{" + OpenApiVisitorBase.EncodeJsonPointerSegment(parameter.Name) + "}") || context.PathString.Contains("#/components")))
{
context.Enter("in");
context.CreateError(
nameof(PathParameterShouldBeInThePath),
$"Declared path parameter \"{parameter.Name}\" needs to be defined as a path parameter at either the path or operation level");
context.Exit();
}
});
// add more rule.
}
}