Пример #1
0
        private OpenApiRequestBody GenerateRequestBodyFromBodyParameter(
            ApiDescription apiDescription,
            SchemaRepository schemaRepository,
            ApiParameterDescription bodyParameter)
        {
            var contentTypes = InferRequestContentTypes(apiDescription);

            var isRequired = bodyParameter.CustomAttributes().Any(attr => RequiredAttributeTypes.Contains(attr.GetType()));

            return(new OpenApiRequestBody
            {
                Content = contentTypes
                          .ToDictionary(
                    contentType => contentType,
                    contentType => new OpenApiMediaType
                {
                    Schema = _schemaGenerator.GenerateSchema(bodyParameter.Type, schemaRepository)
                }
                    ),
                Required = isRequired
            });
        }
Пример #2
0
        private OpenApiRequestBody GenerateRequestBody(
            ApiDescription apiDescription,
            SchemaRepository schemaRepository)
        {
            var bodyParameter = apiDescription.ParameterDescriptions
                                .FirstOrDefault(paramDesc => paramDesc.IsFromBody());

            if (bodyParameter != null)
            {
                return(GenerateRequestBodyFromBodyParameter(apiDescription, schemaRepository, bodyParameter));
            }

            var formParameters = apiDescription.ParameterDescriptions
                                 .Where(paramDesc => paramDesc.IsFromForm());

            if (formParameters.Any())
            {
                return(GenerateRequestBodyFromFormParameters(apiDescription, schemaRepository, formParameters));
            }

            return(null);
        }
Пример #3
0
        protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository)
        {
            if (!schemaRepository.TryGetIdFor(type, out string schemaId))
            {
                schemaId = Options.SchemaIdSelector(type);
                schemaRepository.ReserveIdFor(type, schemaId);

                if (type == typeof(DataTable))
                {
                    schemaRepository.AddSchemaFor(type, CreateDataTableSchema(schemaRepository));
                }
                else if (type == typeof(Exception))
                {
                    schemaRepository.AddSchemaFor(type, CreateExceptionSchema(schemaRepository));
                }
            }

            return(new OpenApiSchema
            {
                Reference = new OpenApiReference {
                    Id = schemaId, Type = ReferenceType.Schema
                }
            });
        }
Пример #4
0
        public OpenApiDocument GetSwagger(string documentName, string host = null, string basePath = null)
        {
            if (!_options.SwaggerDocs.TryGetValue(documentName, out OpenApiInfo info))
            {
                throw new UnknownSwaggerDocument(documentName, _options.SwaggerDocs.Select(d => d.Key));
            }

            var applicableApiDescriptions = _apiDescriptionsProvider.ApiDescriptionGroups.Items
                                            .SelectMany(group => group.Items)
                                            .Where(apiDesc => !(_options.IgnoreObsoleteActions && apiDesc.CustomAttributes().OfType <ObsoleteAttribute>().Any()))
                                            .Where(apiDesc => _options.DocInclusionPredicate(documentName, apiDesc));

            var schemaRepository = new SchemaRepository();

            var swaggerDoc = new OpenApiDocument
            {
                Info       = info,
                Servers    = GenerateServers(host, basePath),
                Paths      = GeneratePaths(applicableApiDescriptions, schemaRepository),
                Components = new OpenApiComponents
                {
                    Schemas         = schemaRepository.Schemas,
                    SecuritySchemes = _options.SecuritySchemes
                },
                SecurityRequirements = _options.SecurityRequirements
            };

            var filterContext = new DocumentFilterContext(applicableApiDescriptions, _schemaGenerator, schemaRepository);

            foreach (var filter in _options.DocumentFilters)
            {
                filter.Apply(swaggerDoc, filterContext);
            }

            return(swaggerDoc);
        }
Пример #5
0
        private OpenApiSchema GeneratePropertySchema(
            JsonProperty jsonProperty,
            MemberInfo memberInfo,
            object[] attributes,
            SchemaRepository schemaRepository)
        {
            var schema = RootGenerator.GenerateSchema(jsonProperty.PropertyType, schemaRepository);

            schema.WriteOnly = jsonProperty.Writable && !jsonProperty.Readable;
            schema.ReadOnly  = jsonProperty.Readable && !jsonProperty.Writable;

            foreach (var attribute in attributes)
            {
                if (attribute is DefaultValueAttribute defaultValue)
                {
                    schema.Default = OpenApiAnyFactory.TryCreateFor(schema, defaultValue.Value, out IOpenApiAny openApiAny)
                        ? openApiAny
                        : schema.Default;
                }
                else if (attribute is RegularExpressionAttribute regex)
                {
                    schema.Pattern = regex.Pattern;
                }
                else if (attribute is RangeAttribute range)
                {
                    schema.Maximum = decimal.TryParse(range.Maximum.ToString(), out decimal maximum)
                        ? maximum
                        : schema.Maximum;

                    schema.Minimum = decimal.TryParse(range.Minimum.ToString(), out decimal minimum)
                        ? minimum
                        : schema.Minimum;
                }
                else if (attribute is MinLengthAttribute minLength)
                {
                    schema.MinLength = minLength.Length;
                }
                else if (attribute is MaxLengthAttribute maxLength)
                {
                    schema.MaxLength = maxLength.Length;
                }
                else if (attribute is StringLengthAttribute stringLength)
                {
                    schema.MinLength = stringLength.MinimumLength;
                    schema.MaxLength = stringLength.MaximumLength;
                }
                else if (attribute is EmailAddressAttribute)
                {
                    schema.Format = "email";
                }
                else if (attribute is CreditCardAttribute)
                {
                    schema.Format = "credit-card";
                }
                else if (attribute is PhoneAttribute)
                {
                    schema.Format = "tel";
                }
                else if (attribute is DataTypeAttribute dataTypeAttribute && schema.Type == "string")
                {
                    schema.Format = DataTypeFormatMap.TryGetValue(dataTypeAttribute.DataType, out string format)
                        ? format
                        : schema.Format;
                }
            }

            return(schema);
        }
Пример #6
0
 protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository)
 {
     return(Options.CustomTypeMappings.ContainsKey(type)
         ? Options.CustomTypeMappings[type]()
         : KnownTypeMappings[type]());
 }
Пример #7
0
 protected abstract OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository);
Пример #8
0
        private OpenApiPaths GeneratePaths(IEnumerable <ApiDescription> apiDescriptions, SchemaRepository schemaRepository)
        {
            var apiDescriptionsByPath = apiDescriptions
                                        .OrderBy(_options.SortKeySelector)
                                        .GroupBy(apiDesc => apiDesc.RelativePathSansQueryString());

            var paths = new OpenApiPaths();

            foreach (var group in apiDescriptionsByPath)
            {
                paths.Add($"/{group.Key}",
                          new OpenApiPathItem
                {
                    Operations = GenerateOperations(group, schemaRepository)
                });
            }
            ;

            return(paths);
        }
Пример #9
0
        private IList <OpenApiParameter> GenerateParameters(ApiDescription apiDescription, SchemaRepository schemaRespository)
        {
            var applicableApiParameters = apiDescription.ParameterDescriptions
                                          .Where(apiParam =>
            {
                return((!apiParam.IsFromBody() && !apiParam.IsFromForm()) &&
                       (apiParam.ModelMetadata == null || apiParam.ModelMetadata.IsBindingAllowed));
            });

            return(applicableApiParameters
                   .Select(apiParam => GenerateParameter(apiParam, schemaRespository))
                   .ToList());
        }