-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathOpenApiSchemaExtensions.cs
More file actions
84 lines (76 loc) · 3.2 KB
/
OpenApiSchemaExtensions.cs
File metadata and controls
84 lines (76 loc) · 3.2 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
using System;
using System.Linq;
using System.Text;
using Microsoft.OpenApi.Models;
namespace Swashbuckle.AspNetCore.ApiTesting
{
public static class OpenApiSchemaExtensions
{
internal static bool TryParse(this OpenApiSchema schema, string stringValue, out object typedValue)
{
typedValue = null;
if (schema.Type == JsonSchemaTypes.Integer && schema.Format == "int64" && long.TryParse(stringValue, out long longValue))
{
typedValue = longValue;
}
else if (schema.Type == JsonSchemaTypes.Integer && int.TryParse(stringValue, out int intValue))
{
typedValue = intValue;
}
else if (schema.Type == JsonSchemaTypes.Number && schema.Format == "double" && double.TryParse(stringValue, out double doubleValue))
{
typedValue = doubleValue;
}
else if (schema.Type == JsonSchemaTypes.Number && float.TryParse(stringValue, out float floatValue))
{
typedValue = floatValue;
}
else if (schema.Type == JsonSchemaTypes.String && schema.Format == "byte" && byte.TryParse(stringValue, out byte byteValue))
{
typedValue = byteValue;
}
else if (schema.Type == JsonSchemaTypes.Boolean && bool.TryParse(stringValue, out bool boolValue))
{
typedValue = boolValue;
}
else if (schema.Type == JsonSchemaTypes.String && schema.Format == "date" && DateTime.TryParse(stringValue, out DateTime dateValue))
{
typedValue = dateValue;
}
else if (schema.Type == JsonSchemaTypes.String && schema.Format == "date-time" && DateTime.TryParse(stringValue, out DateTime dateTimeValue))
{
typedValue = dateTimeValue;
}
else if (schema.Type == JsonSchemaTypes.String && schema.Format == "uuid" && Guid.TryParse(stringValue, out Guid uuidValue))
{
typedValue = uuidValue;
}
else if (schema.Type == JsonSchemaTypes.String)
{
typedValue = stringValue;
}
else if (schema.Type == JsonSchemaTypes.Array)
{
var arrayValue = (schema.Items == null)
? stringValue.Split(',')
: stringValue.Split(',').Select(itemStringValue =>
{
schema.Items.TryParse(itemStringValue, out object itemTypedValue);
return itemTypedValue;
});
typedValue = !arrayValue.Any(itemTypedValue => itemTypedValue == null) ? arrayValue : null;
}
return typedValue != null;
}
internal static string TypeIdentifier(this OpenApiSchema schema)
{
var idBuilder = new StringBuilder();
idBuilder.Append(schema.Type);
if (schema.Type == JsonSchemaTypes.Array && schema.Items != null)
{
idBuilder.Append($"[{schema.Items.Type}]");
}
return idBuilder.ToString();
}
}
}