-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathJsonArrayValidator.cs
More file actions
63 lines (54 loc) · 2.16 KB
/
JsonArrayValidator.cs
File metadata and controls
63 lines (54 loc) · 2.16 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
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Linq;
namespace Swashbuckle.AspNetCore.ApiTesting
{
public class JsonArrayValidator(IJsonValidator jsonValidator) : IJsonValidator
{
private readonly IJsonValidator _jsonValidator = jsonValidator;
public bool CanValidate(OpenApiSchema schema) => schema.Type == "array";
public bool Validate(
OpenApiSchema schema,
OpenApiDocument openApiDocument,
JToken instance,
out IEnumerable<string> errorMessages)
{
if (instance.Type != JTokenType.Array)
{
errorMessages = [$"Path: {instance.Path}. Instance is not of type 'array'"];
return false;
}
var arrayInstance = (JArray)instance;
var errorMessagesList = new List<string>();
// items
if (schema.Items != null)
{
foreach (var itemInstance in arrayInstance)
{
if (!_jsonValidator.Validate(schema.Items, openApiDocument, itemInstance, out IEnumerable<string> itemErrorMessages))
{
errorMessagesList.AddRange(itemErrorMessages);
}
}
}
// maxItems
if (schema.MaxItems.HasValue && (arrayInstance.Count > schema.MaxItems.Value))
{
errorMessagesList.Add($"Path: {instance.Path}. Array size is greater than maxItems");
}
// minItems
if (schema.MinItems.HasValue && (arrayInstance.Count < schema.MinItems.Value))
{
errorMessagesList.Add($"Path: {instance.Path}. Array size is less than minItems");
}
// uniqueItems
if (schema.UniqueItems.HasValue && (arrayInstance.Count != arrayInstance.Distinct().Count()))
{
errorMessagesList.Add($"Path: {instance.Path}. Array does not contain uniqueItems");
}
errorMessages = errorMessagesList;
return !errorMessages.Any();
}
}
}