-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
SchemaGenerator.cs
491 lines (403 loc) · 20 KB
/
SchemaGenerator.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
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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
namespace Swashbuckle.AspNetCore.SwaggerGen
{
public class SchemaGenerator : ISchemaGenerator
{
private readonly SchemaGeneratorOptions _generatorOptions;
private readonly ISerializerDataContractResolver _serializerDataContractResolver;
public SchemaGenerator(SchemaGeneratorOptions generatorOptions, ISerializerDataContractResolver serializerDataContractResolver)
{
_generatorOptions = generatorOptions;
_serializerDataContractResolver = serializerDataContractResolver;
}
public OpenApiSchema GenerateSchema(
Type modelType,
SchemaRepository schemaRepository,
MemberInfo memberInfo = null,
ParameterInfo parameterInfo = null,
ApiParameterRouteInfo routeInfo = null)
{
if (memberInfo != null)
return GenerateSchemaForMember(modelType, schemaRepository, memberInfo);
if (parameterInfo != null)
return GenerateSchemaForParameter(modelType, schemaRepository, parameterInfo, routeInfo);
return GenerateSchemaForType(modelType, schemaRepository);
}
private OpenApiSchema GenerateSchemaForMember(
Type modelType,
SchemaRepository schemaRepository,
MemberInfo memberInfo,
DataProperty dataProperty = null)
{
var dataContract = GetDataContractFor(modelType);
var schema = _generatorOptions.UseOneOfForPolymorphism && IsBaseTypeWithKnownTypesDefined(dataContract, out var knownTypesDataContracts)
? GeneratePolymorphicSchema(dataContract, schemaRepository, knownTypesDataContracts)
: GenerateConcreteSchema(dataContract, schemaRepository);
if (_generatorOptions.UseAllOfToExtendReferenceSchemas && schema.Reference != null)
{
schema.AllOf = new[] { new OpenApiSchema { Reference = schema.Reference } };
schema.Reference = null;
}
if (schema.Reference == null)
{
var customAttributes = memberInfo.GetInlineAndMetadataAttributes();
// Nullable, ReadOnly & WriteOnly are only relevant for Schema "properties" (i.e. where dataProperty is non-null)
if (dataProperty != null)
{
var requiredAttribute = customAttributes.OfType<RequiredAttribute>().FirstOrDefault();
schema.Nullable = _generatorOptions.SupportNonNullableReferenceTypes
? dataProperty.IsNullable && requiredAttribute==null && !memberInfo.IsNonNullableReferenceType()
: dataProperty.IsNullable && requiredAttribute==null;
schema.ReadOnly = dataProperty.IsReadOnly;
schema.WriteOnly = dataProperty.IsWriteOnly;
schema.MinLength = modelType == typeof(string) && requiredAttribute is { AllowEmptyStrings: false } ? 1 : null;
}
var defaultValueAttribute = customAttributes.OfType<DefaultValueAttribute>().FirstOrDefault();
if (defaultValueAttribute != null)
{
var defaultAsJson = dataContract.JsonConverter(defaultValueAttribute.Value);
schema.Default = OpenApiAnyFactory.CreateFromJson(defaultAsJson);
}
var obsoleteAttribute = customAttributes.OfType<ObsoleteAttribute>().FirstOrDefault();
if (obsoleteAttribute != null)
{
schema.Deprecated = true;
}
// NullableAttribute behaves diffrently for Dictionaries
if (schema.AdditionalPropertiesAllowed && modelType.IsGenericType && modelType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
schema.AdditionalProperties.Nullable = !memberInfo.IsDictionaryValueNonNullable();
}
schema.ApplyValidationAttributes(customAttributes);
ApplyFilters(schema, modelType, schemaRepository, memberInfo: memberInfo);
}
return schema;
}
private OpenApiSchema GenerateSchemaForParameter(
Type modelType,
SchemaRepository schemaRepository,
ParameterInfo parameterInfo,
ApiParameterRouteInfo routeInfo)
{
var dataContract = GetDataContractFor(modelType);
var schema = _generatorOptions.UseOneOfForPolymorphism && IsBaseTypeWithKnownTypesDefined(dataContract, out var knownTypesDataContracts)
? GeneratePolymorphicSchema(dataContract, schemaRepository, knownTypesDataContracts)
: GenerateConcreteSchema(dataContract, schemaRepository);
if (_generatorOptions.UseAllOfToExtendReferenceSchemas && schema.Reference != null)
{
schema.AllOf = new[] { new OpenApiSchema { Reference = schema.Reference } };
schema.Reference = null;
}
if (schema.Reference == null)
{
var customAttributes = parameterInfo.GetCustomAttributes();
var defaultValue = parameterInfo.HasDefaultValue
? parameterInfo.DefaultValue
: customAttributes.OfType<DefaultValueAttribute>().FirstOrDefault()?.Value;
if (defaultValue != null)
{
var defaultAsJson = dataContract.JsonConverter(defaultValue);
schema.Default = OpenApiAnyFactory.CreateFromJson(defaultAsJson);
}
schema.ApplyValidationAttributes(customAttributes);
if (routeInfo != null)
{
schema.ApplyRouteConstraints(routeInfo);
}
ApplyFilters(schema, modelType, schemaRepository, parameterInfo: parameterInfo);
}
return schema;
}
private OpenApiSchema GenerateSchemaForType(Type modelType, SchemaRepository schemaRepository)
{
var dataContract = GetDataContractFor(modelType);
var schema = _generatorOptions.UseOneOfForPolymorphism && IsBaseTypeWithKnownTypesDefined(dataContract, out var knownTypesDataContracts)
? GeneratePolymorphicSchema(dataContract, schemaRepository, knownTypesDataContracts)
: GenerateConcreteSchema(dataContract, schemaRepository);
if (schema.Reference == null)
{
ApplyFilters(schema, modelType, schemaRepository);
}
return schema;
}
private DataContract GetDataContractFor(Type modelType)
{
var effectiveType = Nullable.GetUnderlyingType(modelType) ?? modelType;
return _serializerDataContractResolver.GetDataContractForType(effectiveType);
}
private bool IsBaseTypeWithKnownTypesDefined(DataContract dataContract, out IEnumerable<DataContract> knownTypesDataContracts)
{
knownTypesDataContracts = null;
if (dataContract.DataType != DataType.Object) return false;
var subTypes = _generatorOptions.SubTypesSelector(dataContract.UnderlyingType);
if (!subTypes.Any()) return false;
var knownTypes = !dataContract.UnderlyingType.IsAbstract
? new[] { dataContract.UnderlyingType }.Union(subTypes)
: subTypes;
knownTypesDataContracts = knownTypes.Select(knownType => GetDataContractFor(knownType));
return true;
}
private OpenApiSchema GeneratePolymorphicSchema(
DataContract dataContract,
SchemaRepository schemaRepository,
IEnumerable<DataContract> knownTypesDataContracts)
{
return new OpenApiSchema
{
OneOf = knownTypesDataContracts
.Select(allowedTypeDataContract => GenerateConcreteSchema(allowedTypeDataContract, schemaRepository))
.ToList()
};
}
private OpenApiSchema GenerateConcreteSchema(DataContract dataContract, SchemaRepository schemaRepository)
{
if (TryGetCustomTypeMapping(dataContract.UnderlyingType, out Func<OpenApiSchema> customSchemaFactory))
{
return customSchemaFactory();
}
if (dataContract.UnderlyingType.IsAssignableToOneOf(typeof(IFormFile), typeof(FileResult)))
{
return new OpenApiSchema { Type = "string", Format = "binary" };
}
Func<OpenApiSchema> schemaFactory;
bool returnAsReference;
switch (dataContract.DataType)
{
case DataType.Boolean:
case DataType.Integer:
case DataType.Number:
case DataType.String:
{
schemaFactory = () => CreatePrimitiveSchema(dataContract);
returnAsReference = dataContract.UnderlyingType.IsEnum && !_generatorOptions.UseInlineDefinitionsForEnums;
break;
}
case DataType.Array:
{
schemaFactory = () => CreateArraySchema(dataContract, schemaRepository);
returnAsReference = dataContract.UnderlyingType == dataContract.ArrayItemType;
break;
}
case DataType.Dictionary:
{
schemaFactory = () => CreateDictionarySchema(dataContract, schemaRepository);
returnAsReference = dataContract.UnderlyingType == dataContract.DictionaryValueType;
break;
}
case DataType.Object:
{
schemaFactory = () => CreateObjectSchema(dataContract, schemaRepository);
returnAsReference = true;
break;
}
default:
{
schemaFactory = () => new OpenApiSchema();
returnAsReference = false;
break;
}
}
return returnAsReference
? GenerateReferencedSchema(dataContract, schemaRepository, schemaFactory)
: schemaFactory();
}
private bool TryGetCustomTypeMapping(Type modelType, out Func<OpenApiSchema> schemaFactory)
{
return _generatorOptions.CustomTypeMappings.TryGetValue(modelType, out schemaFactory)
|| (modelType.IsConstructedGenericType && _generatorOptions.CustomTypeMappings.TryGetValue(modelType.GetGenericTypeDefinition(), out schemaFactory));
}
private OpenApiSchema CreatePrimitiveSchema(DataContract dataContract)
{
var schema = new OpenApiSchema
{
Type = dataContract.DataType.ToString().ToLower(CultureInfo.InvariantCulture),
Format = dataContract.DataFormat
};
// For backcompat only - EnumValues is obsolete
if (dataContract.EnumValues != null)
{
schema.Enum = dataContract.EnumValues
.Select(value => JsonSerializer.Serialize(value))
.Distinct()
.Select(valueAsJson => OpenApiAnyFactory.CreateFromJson(valueAsJson))
.ToList();
return schema;
}
if (dataContract.UnderlyingType.IsEnum)
{
schema.Enum = dataContract.UnderlyingType.GetEnumValues()
.Cast<object>()
.Select(value => dataContract.JsonConverter(value))
.Distinct()
.Select(valueAsJson => OpenApiAnyFactory.CreateFromJson(valueAsJson))
.ToList();
}
return schema;
}
private OpenApiSchema CreateArraySchema(DataContract dataContract, SchemaRepository schemaRepository)
{
var hasUniqueItems = dataContract.UnderlyingType.IsConstructedFrom(typeof(ISet<>), out _)
|| dataContract.UnderlyingType.IsConstructedFrom(typeof(KeyedCollection<,>), out _);
return new OpenApiSchema
{
Type = "array",
Items = GenerateSchema(dataContract.ArrayItemType, schemaRepository),
UniqueItems = hasUniqueItems ? (bool?)true : null
};
}
private OpenApiSchema CreateDictionarySchema(DataContract dataContract, SchemaRepository schemaRepository)
{
if (dataContract.DictionaryKeys != null)
{
// This is a special case where the set of key values is known (e.g. if the key type is an enum)
return new OpenApiSchema
{
Type = "object",
Properties = dataContract.DictionaryKeys.ToDictionary(
name => name,
name => GenerateSchema(dataContract.DictionaryValueType, schemaRepository)),
AdditionalPropertiesAllowed = false,
};
}
else
{
return new OpenApiSchema
{
Type = "object",
AdditionalPropertiesAllowed = true,
AdditionalProperties = GenerateSchema(dataContract.DictionaryValueType, schemaRepository)
};
}
}
private OpenApiSchema CreateObjectSchema(DataContract dataContract, SchemaRepository schemaRepository)
{
var schema = new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>(),
Required = new SortedSet<string>(),
AdditionalPropertiesAllowed = false
};
var applicableDataProperties = dataContract.ObjectProperties;
if (_generatorOptions.UseAllOfForInheritance || _generatorOptions.UseOneOfForPolymorphism)
{
if (IsKnownSubType(dataContract, out var baseTypeDataContract))
{
var baseTypeSchema = GenerateConcreteSchema(baseTypeDataContract, schemaRepository);
schema.AllOf.Add(baseTypeSchema);
applicableDataProperties = applicableDataProperties
.Where(dataProperty => dataProperty.MemberInfo.DeclaringType == dataContract.UnderlyingType);
}
if (IsBaseTypeWithKnownTypesDefined(dataContract, out var knownTypesDataContracts))
{
foreach (var knownTypeDataContract in knownTypesDataContracts)
{
// Ensure schema is generated for all known types
GenerateConcreteSchema(knownTypeDataContract, schemaRepository);
}
if (TryGetDiscriminatorFor(dataContract, schemaRepository, knownTypesDataContracts, out var discriminator))
{
schema.Properties.Add(discriminator.PropertyName, new OpenApiSchema { Type = "string" });
schema.Required.Add(discriminator.PropertyName);
schema.Discriminator = discriminator;
}
}
}
foreach (var dataProperty in applicableDataProperties)
{
var customAttributes = dataProperty.MemberInfo?.GetInlineAndMetadataAttributes() ?? Enumerable.Empty<object>();
if (_generatorOptions.IgnoreObsoleteProperties && customAttributes.OfType<ObsoleteAttribute>().Any())
continue;
schema.Properties[dataProperty.Name] = (dataProperty.MemberInfo != null)
? GenerateSchemaForMember(dataProperty.MemberType, schemaRepository, dataProperty.MemberInfo, dataProperty)
: GenerateSchemaForType(dataProperty.MemberType, schemaRepository);
if ((dataProperty.IsRequired || customAttributes.OfType<RequiredAttribute>().Any())
&& !schema.Required.Contains(dataProperty.Name))
{
schema.Required.Add(dataProperty.Name);
}
}
if (dataContract.ObjectExtensionDataType != null)
{
schema.AdditionalPropertiesAllowed = true;
schema.AdditionalProperties = GenerateSchema(dataContract.ObjectExtensionDataType, schemaRepository);
}
return schema;
}
private bool IsKnownSubType(DataContract dataContract, out DataContract baseTypeDataContract)
{
baseTypeDataContract = null;
var baseType = dataContract.UnderlyingType.BaseType;
if (baseType == null || baseType == typeof(object) || !_generatorOptions.SubTypesSelector(baseType).Contains(dataContract.UnderlyingType))
return false;
baseTypeDataContract = GetDataContractFor(baseType);
return true;
}
private bool TryGetDiscriminatorFor(
DataContract dataContract,
SchemaRepository schemaRepository,
IEnumerable<DataContract> knownTypesDataContracts,
out OpenApiDiscriminator discriminator)
{
discriminator = null;
var discriminatorName = _generatorOptions.DiscriminatorNameSelector(dataContract.UnderlyingType)
?? dataContract.ObjectTypeNameProperty;
if (discriminatorName == null) return false;
discriminator = new OpenApiDiscriminator
{
PropertyName = discriminatorName
};
foreach (var knownTypeDataContract in knownTypesDataContracts)
{
var discriminatorValue = _generatorOptions.DiscriminatorValueSelector(knownTypeDataContract.UnderlyingType)
?? knownTypeDataContract.ObjectTypeNameValue;
if (discriminatorValue == null) continue;
discriminator.Mapping.Add(discriminatorValue, GenerateConcreteSchema(knownTypeDataContract, schemaRepository).Reference.ReferenceV3);
}
return true;
}
private OpenApiSchema GenerateReferencedSchema(
DataContract dataContract,
SchemaRepository schemaRepository,
Func<OpenApiSchema> definitionFactory)
{
if (schemaRepository.TryLookupByType(dataContract.UnderlyingType, out OpenApiSchema referenceSchema))
return referenceSchema;
var schemaId = _generatorOptions.SchemaIdSelector(dataContract.UnderlyingType);
schemaRepository.RegisterType(dataContract.UnderlyingType, schemaId);
var schema = definitionFactory();
ApplyFilters(schema, dataContract.UnderlyingType, schemaRepository);
return schemaRepository.AddDefinition(schemaId, schema);
}
private void ApplyFilters(
OpenApiSchema schema,
Type type,
SchemaRepository schemaRepository,
MemberInfo memberInfo = null,
ParameterInfo parameterInfo = null)
{
var filterContext = new SchemaFilterContext(
type: type,
schemaGenerator: this,
schemaRepository: schemaRepository,
memberInfo: memberInfo,
parameterInfo: parameterInfo);
foreach (var filter in _generatorOptions.SchemaFilters)
{
filter.Apply(schema, filterContext);
}
}
}
}