-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathOpenApiOperationExtensions.cs
45 lines (42 loc) · 2.1 KB
/
OpenApiOperationExtensions.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.OpenApi.Models;
namespace Kiota.Builder.Extensions {
public static class OpenApiOperationExtensions {
private static readonly HashSet<string> successCodes = new(StringComparer.OrdinalIgnoreCase) {"200", "201", "202"}; //204 excluded as it won't have a schema
private static readonly HashSet<string> structuredMimeTypes = new (StringComparer.OrdinalIgnoreCase) {
"application/json",
"application/xml",
"text/plain",
"text/xml",
"text/yaml",
};
/// <summary>
/// cleans application/vnd.github.mercy-preview+json to application/json
/// </summary>
private static readonly Regex vendorSpecificCleanup = new(@"[^/]+\+", RegexOptions.Compiled);
public static OpenApiSchema GetResponseSchema(this OpenApiOperation operation)
{
// Return Schema that represents all the possible success responses!
var schemas = operation.Responses.Where(r => successCodes.Contains(r.Key))
.SelectMany(re => re.Value.GetResponseSchemas());
return schemas.FirstOrDefault();
}
public static IEnumerable<OpenApiSchema> GetResponseSchemas(this OpenApiResponse response)
{
var schemas = response.Content
.Where(c => !string.IsNullOrEmpty(c.Key))
.Select(c => (Key: c.Key.Split(';', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(), c.Value))
.Where(c => structuredMimeTypes.Contains(c.Key) || structuredMimeTypes.Contains(vendorSpecificCleanup.Replace(c.Key, string.Empty)))
.Select(co => co.Value.Schema)
.Where(s => s is not null);
return schemas;
}
public static OpenApiSchema GetResponseSchema(this OpenApiResponse response)
{
return response.GetResponseSchemas().FirstOrDefault();
}
}
}