-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathJsonObjectValidator.cs
More file actions
80 lines (67 loc) · 2.96 KB
/
JsonObjectValidator.cs
File metadata and controls
80 lines (67 loc) · 2.96 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
76
77
78
79
80
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Linq;
namespace Swashbuckle.AspNetCore.ApiTesting
{
public class JsonObjectValidator(IJsonValidator jsonValidator) : IJsonValidator
{
private readonly IJsonValidator _jsonValidator = jsonValidator;
public bool CanValidate(OpenApiSchema schema) => schema.Type == JsonSchemaTypes.Object;
public bool Validate(
OpenApiSchema schema,
OpenApiDocument openApiDocument,
JToken instance,
out IEnumerable<string> errorMessages)
{
if (instance.Type != JTokenType.Object)
{
errorMessages = [$"Path: {instance.Path}. Instance is not of type 'object'"];
return false;
}
var jObject = (JObject)instance;
var properties = jObject.Properties();
var errorMessagesList = new List<string>();
// maxProperties
if (schema.MaxProperties.HasValue && properties.Count() > schema.MaxProperties.Value)
{
errorMessagesList.Add($"Path: {instance.Path}. Number of properties is greater than maxProperties");
}
// minProperties
if (schema.MinProperties.HasValue && properties.Count() < schema.MinProperties.Value)
{
errorMessagesList.Add($"Path: {instance.Path}. Number of properties is less than minProperties");
}
// required
if (schema.Required != null && schema.Required.Except(properties.Select(p => p.Name)).Any())
{
errorMessagesList.Add($"Path: {instance.Path}. Required property(s) not present");
}
foreach (var property in properties)
{
// properties
IEnumerable<string> propertyErrorMessages;
if (schema.Properties != null && schema.Properties.TryGetValue(property.Name, out OpenApiSchema propertySchema))
{
if (!_jsonValidator.Validate(propertySchema, openApiDocument, property.Value, out propertyErrorMessages))
{
errorMessagesList.AddRange(propertyErrorMessages);
}
continue;
}
if (!schema.AdditionalPropertiesAllowed)
{
errorMessagesList.Add($"Path: {instance.Path}. Additional properties not allowed");
}
// additionalProperties
if (schema.AdditionalProperties != null &&
!_jsonValidator.Validate(schema.AdditionalProperties, openApiDocument, property.Value, out propertyErrorMessages))
{
errorMessagesList.AddRange(propertyErrorMessages);
}
}
errorMessages = errorMessagesList;
return !errorMessages.Any();
}
}
}