-
Notifications
You must be signed in to change notification settings - Fork 241
/
OpenApiSchemaRules.cs
84 lines (70 loc) · 3 KB
/
OpenApiSchemaRules.cs
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
76
77
78
79
80
81
82
83
84
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Properties;
using System.Collections.Generic;
namespace Microsoft.OpenApi.Validations.Rules
{
/// <summary>
/// The validation rules for <see cref="OpenApiSchema"/>.
/// </summary>
[OpenApiRule]
public static class OpenApiSchemaRules
{
/// <summary>
/// Validate the data matches with the given data type.
/// </summary>
public static ValidationRule<OpenApiSchema> SchemaMismatchedDataType =>
new ValidationRule<OpenApiSchema>(
(context, schema) =>
{
// default
context.Enter("default");
if (schema.Default != null)
{
RuleHelpers.ValidateDataTypeMismatch(context, nameof(SchemaMismatchedDataType), schema.Default, schema);
}
context.Exit();
// example
context.Enter("example");
if (schema.Example != null)
{
RuleHelpers.ValidateDataTypeMismatch(context, nameof(SchemaMismatchedDataType), schema.Example, schema);
}
context.Exit();
// enum
context.Enter("enum");
if (schema.Enum != null)
{
for (int i = 0; i < schema.Enum.Count; i++)
{
context.Enter(i.ToString());
RuleHelpers.ValidateDataTypeMismatch(context, nameof(SchemaMismatchedDataType), schema.Enum[i], schema);
context.Exit();
}
}
context.Exit();
});
/// <summary>
/// Validates Schema Discriminator
/// </summary>
public static ValidationRule<OpenApiSchema> ValidateSchemaDiscriminator =>
new ValidationRule<OpenApiSchema>(
(context, schema) =>
{
// discriminator
context.Enter("discriminator");
if (schema.Reference != null && schema.Discriminator != null)
{
if (!schema.Required.Contains(schema.Discriminator?.PropertyName))
{
context.CreateError(nameof(ValidateSchemaDiscriminator),
string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator,
schema.Reference.Id, schema.Discriminator.PropertyName));
}
}
context.Exit();
});
}
}