-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAsyncApiDocumentRules.cs
More file actions
97 lines (85 loc) · 3.6 KB
/
AsyncApiDocumentRules.cs
File metadata and controls
97 lines (85 loc) · 3.6 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
namespace ByteBard.AsyncAPI.Validation.Rules
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ByteBard.AsyncAPI.Models;
using ByteBard.AsyncAPI.Validations;
[AsyncApiRule]
public static class AsyncApiDocumentRules
{
private static TimeSpan RegexTimeout = TimeSpan.FromSeconds(1);
/// <summary>
/// The key regex.
/// </summary>
private static Regex keyRegex = new Regex(@"^[a-zA-Z0-9\.\-_]+$", RegexOptions.None, RegexTimeout);
public static ValidationRule<AsyncApiDocument> DocumentRequiredFields =>
new ValidationRule<AsyncApiDocument>(
(context, document) =>
{
context.Enter("info");
if (document.Info == null)
{
context.CreateError(
nameof(DocumentRequiredFields),
string.Format(Resource.Validation_FieldRequired, "info", "document"));
}
context.Exit();
});
public static ValidationRule<AsyncApiDocument> ChannelKeyRegex =>
new ValidationRule<AsyncApiDocument>(
(context, document) =>
{
context.Enter("channels");
var hashSet = new HashSet<string>();
foreach (var key in document.Channels?.Keys)
{
if (!keyRegex.IsMatch(key))
{
context.CreateError(
"ChannelKeys",
string.Format(Resource.Validation_KeyMustMatchRegularExpr, key, "channels", keyRegex.ToString()));
}
if (!hashSet.Add(key))
{
context.CreateError("ChannelKey", string.Format(Resource.Validation_ChannelsMustBeUnique));
}
}
context.Exit();
});
public static ValidationRule<AsyncApiDocument> ServerKeyRegex =>
new ValidationRule<AsyncApiDocument>(
(context, document) =>
{
if (document.Servers?.Keys == null)
{
return;
}
context.Enter("servers");
foreach (var key in document.Servers?.Keys)
{
if (!keyRegex.IsMatch(key))
{
context.CreateError(
"ServerKeys",
string.Format(Resource.Validation_KeyMustMatchRegularExpr, key, "servers", keyRegex.ToString()));
}
}
context.Exit();
});
[AsyncApiVersionRule(AsyncApiVersion.AsyncApi2_0)]
public static ValidationRule<AsyncApiDocument> V2ChannelsRequired =>
new ValidationRule<AsyncApiDocument>(
(context, document) =>
{
context.Enter("channels");
if (document.Channels == null || document.Channels.Count == 0)
{
context.CreateError(
nameof(DocumentRequiredFields),
string.Format(Resource.Validation_FieldRequired, "channels", "document"));
}
context.Exit();
});
}
}