-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathOpenApiSchemaGenerator.cs
More file actions
771 lines (679 loc) · 37.3 KB
/
OpenApiSchemaGenerator.cs
File metadata and controls
771 lines (679 loc) · 37.3 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.OData.Edm;
using Microsoft.OpenApi.OData.Properties;
using Microsoft.OpenApi.OData.Edm;
using Microsoft.OpenApi.OData.Common;
using System.Linq;
using Microsoft.OpenApi.MicrosoftExtensions;
using Microsoft.OpenApi.OData.Vocabulary.Core;
using System.Text.Json.Nodes;
using System.Globalization;
namespace Microsoft.OpenApi.OData.Generator
{
/// <summary>
/// Extension methods to create <see cref="OpenApiSchema"/> by <see cref="IEdmModel"/>.
/// </summary>
internal static class OpenApiSchemaGenerator
{
/// <summary>
/// Adds the component schemas to the Open API document.
/// </summary>
/// <param name="context">The OData to Open API context.</param>
/// <param name="document">The Open API document to use for references lookup.</param>
public static void AddSchemasToDocument(this ODataContext context, OpenApiDocument document)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(document, nameof(document));
// append the Edm.Spatial
foreach(var schema in context.CreateSpatialSchemas(document))
{
document.AddComponent(schema.Key, schema.Value);
}
// append the OData errors
foreach(var schema in context.CreateODataErrorSchemas(document))
{
document.AddComponent(schema.Key, schema.Value);
}
if(context.Settings.EnableDollarCountPath)
document.AddComponent(Constants.DollarCountSchemaName, new OpenApiSchema {
Type = JsonSchemaType.Number,
Format = context.Settings.UseInt32ForCountResponses ? "int32" : "int64"
});
if(context.HasAnyNonContainedCollections())
{
document.AddComponent($"String{Constants.CollectionSchemaSuffix}", CreateCollectionSchema(context, new OpenApiSchema { Type = JsonSchemaType.String }, Constants.StringType, document));
}
document.AddComponent(Constants.ReferenceUpdateSchemaName, new OpenApiSchema()
{
Type = JsonSchemaType.Object,
Properties = new Dictionary<string, IOpenApiSchema>
{
{Constants.OdataId, new OpenApiSchema { Type = JsonSchemaType.String }},
{Constants.OdataType, new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null }},
}
});
document.AddComponent(Constants.ReferenceCreateSchemaName, new OpenApiSchema()
{
Type = JsonSchemaType.Object,
Properties = new Dictionary<string, IOpenApiSchema>
{
{Constants.OdataId, new OpenApiSchema { Type = JsonSchemaType.String }}
},
AdditionalProperties = new OpenApiSchema { Type = JsonSchemaType.Object }
});
document.AddComponent(Constants.ReferenceNumericName, new OpenApiSchema()
{
Type = JsonSchemaType.String | JsonSchemaType.Null,
Enum =
[
"-INF",
"INF",
"NaN"
]
});
if (context.Settings.EnableODataAnnotationReferencesForResponses)
{
// @odata.nextLink + @odata.count
if (context.Settings.EnablePagination || context.Settings.EnableCount)
{
var responseSchema = new OpenApiSchema()
{
Title = "Base collection pagination and count responses",
Type = JsonSchemaType.Object,
};
document.AddComponent(Constants.BaseCollectionPaginationCountResponse, responseSchema);
responseSchema.Properties ??= new Dictionary<string, IOpenApiSchema>();
if (context.Settings.EnableCount)
{
var odataCount = ODataConstants.CreateOdataCount(context.Settings.UseInt32ForCountResponses);
responseSchema.Properties.Add(odataCount.Key, odataCount.Value);
}
if (context.Settings.EnablePagination)
responseSchema.Properties.Add(ODataConstants.OdataNextLink.Key, ODataConstants.OdataNextLink.Value);
}
// @odata.nextLink + @odata.deltaLink
if (context.Model.SchemaElements.OfType<IEdmFunction>().Any(static x => x.IsDeltaFunction()))
{
document.AddComponent(Constants.BaseDeltaFunctionResponse, new OpenApiSchema()
{
Title = "Base delta function response",
Type = JsonSchemaType.Object,
Properties = new Dictionary<string, IOpenApiSchema>
{
{ODataConstants.OdataNextLink.Key, ODataConstants.OdataNextLink.Value},
{ODataConstants.OdataDeltaLink.Key, ODataConstants.OdataDeltaLink.Value}
}
});
}
}
// Each entity type, complex type, enumeration type, and type definition directly
// or indirectly used in the paths field is represented as a name / value pair of the schemas map.
// Ideally this would be driven off the types used in the paths, but in practice, it is simply
// all of the types present in the model.
IEnumerable<IEdmSchemaElement> elements = context.Model.GetAllElements();
foreach (var element in elements)
{
switch (element.SchemaElementKind)
{
case EdmSchemaElementKind.TypeDefinition: // Type definition
{
IEdmType reference = (IEdmType)element;
var fullTypeName = reference.FullTypeName();
if(reference is IEdmComplexType &&
fullTypeName.Split(['.'], StringSplitOptions.RemoveEmptyEntries)
.Last()
.Equals(context.Settings.InnerErrorComplexTypeName, StringComparison.Ordinal))
continue;
document.AddComponent(fullTypeName, context.CreateSchemaTypeSchema(reference, document));
}
break;
}
}
foreach(var collectionEntry in context.GetAllCollectionEntityTypes()
.Select(x => new KeyValuePair<string, OpenApiSchema>(
$"{(x is IEdmEntityType eType ? eType.FullName() : x.FullTypeName())}{Constants.CollectionSchemaSuffix}",
CreateCollectionSchema(context, x, document)))
.Concat(context.GetAllCollectionComplexTypes()
.Select(x => new KeyValuePair<string, OpenApiSchema>(
$"{x.FullTypeName()}{Constants.CollectionSchemaSuffix}",
CreateCollectionSchema(context, x, document))))
.ToArray())
{
document.AddComponent(collectionEntry.Key, collectionEntry.Value);
}
}
internal static bool HasAnyNonContainedCollections(this ODataContext context)
{
return context.Model
.SchemaElements
.OfType<IEdmStructuredType>()
.SelectMany(x => x.NavigationProperties())
.Any(x => x.TargetMultiplicity() == EdmMultiplicity.Many && !x.ContainsTarget);
}
internal static IEnumerable<IEdmComplexType> GetAllCollectionComplexTypes(this ODataContext context)
{
return context.Model
.SchemaElements
.OfType<IEdmStructuredType>()
.SelectMany(x => x.StructuralProperties())
.Where(x => x.Type.IsCollection())
.Select(x => x.Type.Definition.AsElementType())
.OfType<IEdmComplexType>()
.Distinct()
.ToList();
}
internal static IEnumerable<IEdmStructuredType> GetAllCollectionEntityTypes(this ODataContext context)
{
var collectionEntityTypes = new HashSet<IEdmStructuredType>(
(context.EntityContainer?
.EntitySets()
.Select(x => x.EntityType) ??
Enumerable.Empty<IEdmStructuredType>())
.Union(context.Model
.SchemaElements
.OfType<IEdmStructuredType>()
.SelectMany(x => x.NavigationProperties())
.Where(x => x.TargetMultiplicity() == EdmMultiplicity.Many)
.Select(x => x.Type.ToStructuredType()))
.Distinct()); // we could include actions and functions but actions are not pageable by nature (OData.NextLink) and functions might have specific annotations (deltalink)
var derivedCollectionTypes = collectionEntityTypes.SelectMany(x => context.Model.FindAllDerivedTypes(x).OfType<IEdmStructuredType>())
.Where(x => !collectionEntityTypes.Contains(x))
.Distinct()
.ToArray();
return collectionEntityTypes.Union(derivedCollectionTypes);
}
private static OpenApiSchema CreateCollectionSchema(ODataContext context, IEdmStructuredType structuredType, OpenApiDocument document)
{
IOpenApiSchema? schema = null;
var entityType = structuredType as IEdmEntityType;
if (context.Settings.EnableDerivedTypesReferencesForResponses && entityType != null)
{
schema = EdmModelHelper.GetDerivedTypesReferenceSchema(entityType, context.Model, document);
}
if (schema == null)
{
schema = new OpenApiSchemaReference(entityType?.FullName() ?? structuredType.FullTypeName(), document);
}
return CreateCollectionSchema(context, schema, entityType?.Name ?? structuredType.FullTypeName(), document);
}
private static OpenApiSchema CreateCollectionSchema(ODataContext context, IOpenApiSchema schema, string typeName, OpenApiDocument document)
{
var properties = new Dictionary<string, IOpenApiSchema>
{
{
"value",
new OpenApiSchema
{
Type = JsonSchemaType.Array,
Items = schema
}
}
};
OpenApiSchema baseSchema = new()
{
Type = JsonSchemaType.Object,
Properties = properties
};
OpenApiSchema collectionSchema;
if (context.Settings.EnablePagination || context.Settings.EnableCount)
{
if (context.Settings.EnableODataAnnotationReferencesForResponses)
{
// @odata.nextLink + @odata.count
var paginationCountSchema = new OpenApiSchemaReference(Constants.BaseCollectionPaginationCountResponse, document);
collectionSchema = new OpenApiSchema
{
AllOf =
[
paginationCountSchema,
baseSchema
]
};
}
else
{
if (context.Settings.EnablePagination)
baseSchema.Properties.Add(ODataConstants.OdataNextLink.Key, ODataConstants.OdataNextLink.Value);
if (context.Settings.EnableCount)
{
var odataCount = ODataConstants.CreateOdataCount(context.Settings.UseInt32ForCountResponses);
baseSchema.Properties.Add(odataCount.Key, odataCount.Value);
}
collectionSchema = baseSchema;
}
}
else
{
collectionSchema = baseSchema;
}
collectionSchema.Title = $"Collection of {typeName}";
collectionSchema.Type = JsonSchemaType.Object;
return collectionSchema;
}
/// <summary>
/// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmEnumType"/>.
/// An enumeration type is represented as a Schema Object of type string containing the OpenAPI Specification enum keyword.
/// Its value is an array that contains a string with the member name for each enumeration member.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="enumType">The Edm enum type.</param>
/// <returns>The created <see cref="OpenApiSchema"/>.</returns>
public static OpenApiSchema CreateEnumTypeSchema(this ODataContext context, IEdmEnumType enumType)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(enumType, nameof(enumType));
OpenApiSchema schema = new()
{
// An enumeration type is represented as a Schema Object of type string
Type = JsonSchemaType.String,
// containing the OpenAPI Specification enum keyword.
Enum = new List<JsonNode>(),
// It optionally can contain the field description,
// whose value is the value of the unqualified annotation Core.Description of the enumeration type.
Description = context.Model.GetDescriptionAnnotation(enumType)
};
// If the enum is flagged, add the extension info to the description
if (context.Settings.AddEnumFlagsExtension && enumType.IsFlags)
{
var enumFlagsExtension = new OpenApiEnumFlagsExtension
{
IsFlags = true,
};
schema.Extensions ??= new Dictionary<string, IOpenApiExtension>();
schema.Extensions.Add(OpenApiEnumFlagsExtension.Name, enumFlagsExtension);
}
var extension = (context.Settings.OpenApiSpecVersion == OpenApiSpecVersion.OpenApi2_0 ||
context.Settings.OpenApiSpecVersion == OpenApiSpecVersion.OpenApi3_0 ||
context.Settings.OpenApiSpecVersion == OpenApiSpecVersion.OpenApi3_1) &&
context.Settings.AddEnumDescriptionExtension ?
new OpenApiEnumValuesDescriptionExtension {
EnumName = enumType.Name,
} :
null;
// Enum value is an array that contains a string with the member name for each enumeration member.
foreach (IEdmEnumMember member in enumType.Members)
{
schema.Enum.Add(member.Name);
AddEnumDescription(member, extension, context);
}
if(extension is {ValuesDescriptions.Count:> 0})
{
schema.Extensions ??= new Dictionary<string, IOpenApiExtension>();
schema.Extensions.Add(OpenApiEnumValuesDescriptionExtension.Name, extension);
}
schema.Title = enumType.Name;
return schema;
}
private static void AddEnumDescription(IEdmEnumMember member, OpenApiEnumValuesDescriptionExtension? target, ODataContext context)
{
if (target == null)
return;
var enumDescription = context.Model.GetDescriptionAnnotation(member);
if(!string.IsNullOrEmpty(enumDescription))
target.ValuesDescriptions.Add(new EnumDescription
{
Name = member.Name,
Value = member.Name,
Description = enumDescription
});
}
/// <summary>
/// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmStructuredType"/>.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="structuredType">The Edm structured type.</param>
/// <param name="document">The Open API document to lookup references.</param>
/// <returns>The created <see cref="OpenApiSchema"/>.</returns>
public static OpenApiSchema CreateStructuredTypeSchema(this ODataContext context, IEdmStructuredType structuredType, OpenApiDocument document)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(structuredType, nameof(structuredType));
Utils.CheckArgumentNull(document, nameof(document));
return context.CreateStructuredTypeSchema(structuredType, true, true, document);
}
/// <summary>
/// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmProperty"/>.
/// Each structural property and navigation property is represented as a name/value pair of the
/// standard OpenAPI properties object. The name is the property name,
/// the value is a Schema Object describing the allowed values of the property.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="property">The Edm property.</param>
/// <param name="document">The Open API document to lookup references.</param>
/// <returns>The created <see cref="IOpenApiSchema"/>.</returns>
public static IOpenApiSchema CreatePropertySchema(this ODataContext context, IEdmProperty property, OpenApiDocument document)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(property, nameof(property));
Utils.CheckArgumentNull(document, nameof(document));
var schema = context.CreateEdmTypeSchema(property.Type, document);
if (schema is OpenApiSchema openApiSchema)
{
if (property.PropertyKind is EdmPropertyKind.Structural &&
property is IEdmStructuralProperty structuralProperty)
{
openApiSchema.Default = CreateDefault(structuralProperty);
}
// The Schema Object for a property optionally can contain the field description,
// whose value is the value of the unqualified annotation Core.Description of the property.
openApiSchema.Description = context.Model.GetDescriptionAnnotation(property);
// Set property with Computed Annotation in CSDL to readonly
openApiSchema.ReadOnly = context.Model.GetBoolean(property, CoreConstants.Computed) ?? false;
}
return schema;
}
/// <summary>
/// Create a map of string/<see cref="OpenApiSchema"/> map for a <see cref="IEdmStructuredType"/>'s all properties.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="structuredType">The Edm structured type.</param>
/// <param name="document">The Open API document to lookup references.</param>
/// <returns>The created map of <see cref="OpenApiSchema"/>.</returns>
public static Dictionary<string, IOpenApiSchema> CreateStructuredTypePropertiesSchema(this ODataContext context, IEdmStructuredType structuredType, OpenApiDocument document)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(structuredType, nameof(structuredType));
// The name is the property name, the value is a Schema Object describing the allowed values of the property.
var properties = new Dictionary<string, IOpenApiSchema>();
// structure properties
foreach (var property in structuredType.DeclaredStructuralProperties())
{
var propertySchema = context.CreatePropertySchema(property, document);
if (propertySchema is OpenApiSchema openApiSchema)
{
openApiSchema.Description = context.Model.GetDescriptionAnnotation(property);
// we always want a new copy because it's a reference
openApiSchema.Extensions = propertySchema.Extensions is null ? [] : new Dictionary<string, IOpenApiExtension>(propertySchema.Extensions);
openApiSchema.Extensions.AddCustomAttributesToExtensions(context, property);
}
properties.Add(property.Name, propertySchema);
}
// navigation properties
foreach (var property in structuredType.DeclaredNavigationProperties())
{
var propertySchema = context.CreateEdmTypeSchema(property.Type, document);
if (propertySchema is OpenApiSchema openApiSchema)
{
openApiSchema.Description = context.Model.GetDescriptionAnnotation(property);
// we always want a new copy because it's a reference
openApiSchema.Extensions = propertySchema.Extensions is null ? [] : new Dictionary<string, IOpenApiExtension>(propertySchema.Extensions);
openApiSchema.Extensions.AddCustomAttributesToExtensions(context, property);
openApiSchema.Extensions.Add(Constants.xMsNavigationProperty, new JsonNodeExtension(true));
}
properties.Add(property.Name, propertySchema);
}
return properties;
}
public static IOpenApiSchema CreateSchemaTypeDefinitionSchema(this ODataContext context, IEdmTypeDefinition typeDefinition, OpenApiDocument document)
{
return context.CreateSchema(typeDefinition.UnderlyingType, document);
}
internal static IOpenApiSchema CreateSchemaTypeSchema(this ODataContext context, IEdmType edmType, OpenApiDocument document)
{
Debug.Assert(context != null);
Debug.Assert(edmType != null);
switch (edmType.TypeKind)
{
case EdmTypeKind.Complex: // complex type
case EdmTypeKind.Entity: // entity type
return context.CreateStructuredTypeSchema((IEdmStructuredType)edmType, true, true, document);
case EdmTypeKind.Enum: // enum type
return context.CreateEnumTypeSchema((IEdmEnumType)edmType);
case EdmTypeKind.TypeDefinition: // type definition
return context.CreateSchemaTypeDefinitionSchema((IEdmTypeDefinition)edmType, document);
case EdmTypeKind.None:
default:
throw Error.NotSupported(string.Format(SRResource.NotSupportedEdmTypeKind, edmType.TypeKind));
}
}
private static OpenApiSchema CreateStructuredTypeSchema(this ODataContext context, IEdmStructuredType structuredType, bool processBase, bool processExample,
OpenApiDocument document,
IEnumerable<IEdmStructuredType>? derivedTypes = null)
{
Debug.Assert(context != null);
Debug.Assert(structuredType != null);
JsonNode? example = null;
if (context.Settings.ShowSchemaExamples)
{
example = CreateStructuredTypePropertiesExample(context, structuredType, document);
}
if (context.Settings.EnableDiscriminatorValue && derivedTypes == null)
{
derivedTypes = context.Model.FindAllDerivedTypes(structuredType);
}
if (processBase && structuredType.BaseType != null)
{
// The x-ms-discriminator-value extension is added to structured types which are derived types.
Dictionary<string, IOpenApiExtension>? extension = null;
if (context.Settings.EnableDiscriminatorValue && (derivedTypes is null || !derivedTypes.Any()))
{
extension = new Dictionary<string, IOpenApiExtension>
{
{ Constants.xMsDiscriminatorValue, new JsonNodeExtension("#" + structuredType.FullTypeName()) }
};
}
// A structured type with a base type is represented as a Schema Object
// that contains the keyword allOf whose value is an array with two items:
return new OpenApiSchema
{
Extensions = extension,
AllOf =
[
// 1. a JSON Reference to the Schema Object of the base type
new OpenApiSchemaReference(structuredType.BaseType.FullTypeName(), document),
// 2. a Schema Object describing the derived type
context.CreateStructuredTypeSchema(structuredType, false, false, document, derivedTypes)
],
AnyOf = null,
OneOf = null,
Properties = null,
Example = example
};
}
else
{
// The discriminator object is added to structured types which have derived types.
OpenApiDiscriminator? discriminator = null;
if (context.Settings.EnableDiscriminatorValue && derivedTypes is not null && derivedTypes.Any())
{
Dictionary<string, OpenApiSchemaReference> mapping = derivedTypes
.Select(x => ($"#{x.FullTypeName()}", new OpenApiSchemaReference(x.FullTypeName(), document)))
.ToDictionary(x => x.Item1, x => x.Item2);
discriminator = new OpenApiDiscriminator
{
PropertyName = Constants.OdataType,
Mapping = mapping
};
}
// A structured type without a base type is represented as a Schema Object of type object
OpenApiSchema schema = new()
{
Title = (structuredType as IEdmSchemaElement)?.Name,
Type = JsonSchemaType.Object,
Discriminator = discriminator,
// Each structural property and navigation property is represented
// as a name/value pair of the standard OpenAPI properties object.
Properties = context.CreateStructuredTypePropertiesSchema(structuredType, document),
// make others null
AllOf = null,
OneOf = null,
AnyOf = null
};
if (context.Settings.EnableDiscriminatorValue)
{
JsonNode? defaultValue = null;
bool isBaseTypeEntity = Constants.EntityName.Equals(structuredType.BaseType?.FullTypeName().Split('.').Last(), StringComparison.OrdinalIgnoreCase);
bool isBaseTypeAbstractNonEntity = (structuredType.BaseType?.IsAbstract ?? false) && !isBaseTypeEntity;
if (!context.Settings.EnableTypeDisambiguationForDefaultValueOfOdataTypeProperty ||
isBaseTypeAbstractNonEntity ||
structuredType.BaseType is not null && context.Model.IsBaseTypeReferencedAsTypeInModel(structuredType.BaseType))
{
defaultValue = "#" + structuredType.FullTypeName();
}
if (!schema.Properties.TryAdd(Constants.OdataType, new OpenApiSchema()
{
Type = JsonSchemaType.String,
Default = defaultValue,
}))
{
throw new InvalidOperationException(
$"Property {Constants.OdataType} is already present in schema {structuredType.FullTypeName()}; verify CSDL.");
}
schema.Required ??= new HashSet<string>();
schema.Required.Add(Constants.OdataType);
}
// It optionally can contain the field description,
// whose value is the value of the unqualified annotation Core.Description of the structured type.
if (structuredType.TypeKind == EdmTypeKind.Complex)
{
IEdmComplexType complex = (IEdmComplexType)structuredType;
schema.Description = context.Model.GetDescriptionAnnotation(complex);
}
else if (structuredType.TypeKind == EdmTypeKind.Entity)
{
IEdmEntityType entity = (IEdmEntityType)structuredType;
schema.Description = context.Model.GetDescriptionAnnotation(entity);
}
if (processExample)
{
schema.Example = example;
}
return schema;
}
}
internal static JsonObject CreateStructuredTypePropertiesExample(ODataContext context, IEdmStructuredType structuredType, OpenApiDocument document)
{
JsonObject example = [];
// properties
foreach (var property in structuredType.Properties())
{
IEdmTypeReference propertyType = property.Type;
JsonNode item = GetTypeNameForExample(context, propertyType, document);
if (propertyType.TypeKind() == EdmTypeKind.Primitive &&
item is JsonValue jsonValue &&
jsonValue.TryGetValue<string>(out var stringAny) &&
structuredType is IEdmEntityType entityType &&
entityType.Key().Any(k => StringComparer.Ordinal.Equals(k.Name, property.Name)))
{
item = $"{stringAny} (identifier)";
}
example.Add(property.Name, item);
}
return example;
}
private static JsonNode? GetTypeNameForPrimitive(ODataContext context, IEdmTypeReference edmTypeReference, OpenApiDocument document)
{
IEdmPrimitiveType primitiveType = edmTypeReference.AsPrimitive().PrimitiveDefinition();
IOpenApiSchema schema = context.CreateSchema(primitiveType, document);
if (edmTypeReference.IsBoolean())
{
return true;
}
else
{
if (schema is OpenApiSchemaReference { Reference.Id: not null } reference && !string.IsNullOrEmpty(reference.Reference.Id))
{
return reference.Reference.Id;
}
else
{
return (schema.Type & ~JsonSchemaType.Null)?.ToIdentifiers()[0] ??
(schema.AnyOf ?? Enumerable.Empty<IOpenApiSchema>())
.Union(schema.AllOf ?? Enumerable.Empty<IOpenApiSchema>())
.Union(schema.OneOf ?? Enumerable.Empty<IOpenApiSchema>())
.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format ?? schema.Format;
}
}
}
private static JsonNode GetTypeNameForExample(ODataContext context, IEdmTypeReference edmTypeReference, OpenApiDocument document)
{
return edmTypeReference.TypeKind() switch
{
// return new OpenApiBinary(new byte[] { 0x00 }); issue on binary writing
EdmTypeKind.Primitive when edmTypeReference.IsBinary() => Convert.ToBase64String(new byte[] { 0x00 }),
EdmTypeKind.Primitive when edmTypeReference.IsBoolean() => true,
EdmTypeKind.Primitive when edmTypeReference.IsByte() => 0x00,
EdmTypeKind.Primitive when edmTypeReference.IsDate() => DateTime.MinValue.ToString("o", CultureInfo.InvariantCulture),
EdmTypeKind.Primitive when edmTypeReference.IsDateTimeOffset() => DateTimeOffset.MinValue.ToString("o", CultureInfo.InvariantCulture),
EdmTypeKind.Primitive when edmTypeReference.IsGuid() => Guid.Empty.ToString("D", CultureInfo.InvariantCulture),
EdmTypeKind.Primitive when edmTypeReference.IsInt16() ||
edmTypeReference.IsInt32() ||
edmTypeReference.IsDecimal() ||
edmTypeReference.IsInt64() ||
edmTypeReference.IsFloating() ||
edmTypeReference.IsDouble() => 0,
EdmTypeKind.Primitive when GetTypeNameForPrimitive(context, edmTypeReference, document) is JsonNode primitiveType => primitiveType,
EdmTypeKind.Entity or EdmTypeKind.Complex => new JsonObject()
{
[Constants.OdataType] = edmTypeReference.FullName()
},
EdmTypeKind.Enum when edmTypeReference.Definition is IEdmEnumType edmEnumType && edmEnumType.Members.FirstOrDefault()?.Name is string firstMemberName =>
JsonValue.Create(firstMemberName),
// in case the enum members are empty which often happens due to hidden members on Microsoft Graph
EdmTypeKind.Enum when edmTypeReference.Definition is IEdmEnumType edmEnumType && edmEnumType.Members.FirstOrDefault()?.Name is null =>
JsonValue.Create(edmTypeReference.FullName()),
EdmTypeKind.Collection => new JsonArray(GetTypeNameForExample(context, edmTypeReference.AsCollection().ElementType(), document)),
EdmTypeKind.TypeDefinition => GetTypeNameForExample(context, new EdmPrimitiveTypeReference(edmTypeReference.AsTypeDefinition().TypeDefinition().UnderlyingType, edmTypeReference.IsNullable), document),
EdmTypeKind.Untyped => new JsonObject(),
_ => throw new OpenApiException("Not support for the type kind " + edmTypeReference.TypeKind()),
};
}
private static JsonNode? CreateDefault(this IEdmStructuralProperty property)
{
if (property == null ||
property.DefaultValueString == null)
{
return null;
}
if (property.Type.IsEnum())
{
return property.DefaultValueString;
}
if (!property.Type.IsPrimitive())
{
return null;
}
IEdmPrimitiveTypeReference primitiveTypeReference = property.Type.AsPrimitive();
switch (primitiveTypeReference.PrimitiveKind())
{
case EdmPrimitiveTypeKind.Boolean:
{
if (bool.TryParse(property.DefaultValueString, out bool result))
{
return result;
}
}
break;
case EdmPrimitiveTypeKind.Int16:
case EdmPrimitiveTypeKind.Int32:
{
if (int.TryParse(property.DefaultValueString, out int result))
{
return result;
}
}
break;
case EdmPrimitiveTypeKind.Int64:
break;
// The type 'System.Double' is not supported in Open API document.
case EdmPrimitiveTypeKind.Double:
/*
{
double result;
if (Double.TryParse(property.DefaultValueString, out result))
{
return new OpenApiDouble((float)result);
}
}*/
break;
}
return property.DefaultValueString;
}
}
}