private Operation CreateGetByIdOperation(SwaggerPathsResource swaggerResource)
 {
     return(new Operation
     {
         tags = new List <string>
         {
             SwaggerDocumentHelper.GetResourcePluralName(swaggerResource.Resource)
             .ToCamelCase()
         },
         summary = "Retrieves a specific resource using the resource's identifier (using the \"Get By Id\" pattern).",
         description = "This GET operation retrieves a resource by the specified resource identifier.",
         operationId = $"get{swaggerResource.Resource.PluralName}ById",
         deprecated = swaggerResource.IsDeprecated,
         produces = new[] { _contentTypeStrategy.GetOperationContentType(swaggerResource, ContentTypeUsage.Readable) },
         parameters = new[]
         {
             // Path parameters need to be inline in the operation, and not referenced.
             SwaggerDocumentHelper.CreateIdParameter(),
             new Parameter {
                 @ref = SwaggerDocumentHelper.GetParameterReference("If-None-Match")
             }
         }.Concat(
             swaggerResource.DefaultGetByIdParameters
             .Select(p => new Parameter {
             @ref = SwaggerDocumentHelper.GetParameterReference(p)
         }))
         .ToList(),
         responses =
             SwaggerDocumentHelper.GetReadOperationResponses(
                 _pathsFactoryNamingStrategy.GetResourceName(swaggerResource, ContentTypeUsage.Readable), false)
     });
 }
        private IList <Parameter> CreateGetByExampleParameters(SwaggerPathsResource swaggerResource)
        {
            var parameterList = CreateQueryParameters()
                                .Concat(
                swaggerResource.DefaultGetByExampleParameters.Select(
                    p => new Parameter {
                @ref = SwaggerDocumentHelper.GetParameterReference(p)
            }))
                                .ToList();

            swaggerResource.RequestProperties.ForEach(
                x =>
            {
                parameterList.Add(
                    new Parameter
                {
                    name = x.PropertyName.ToCamelCase(),
                    @in  = swaggerResource.IsPathParameter(x)
                                ? "path"
                                : "query",
                    description       = SwaggerDocumentHelper.PropertyDescription(x),
                    type              = SwaggerDocumentHelper.PropertyType(x),
                    format            = x.PropertyType.ToOpenApiFormat(),
                    required          = swaggerResource.IsPathParameter(x),
                    isIdentity        = SwaggerDocumentHelper.GetIsIdentity(x),
                    maxLength         = SwaggerDocumentHelper.GetMaxLength(x),
                    isDeprecated      = SwaggerDocumentHelper.GetIsDeprecated(x),
                    deprecatedReasons = SwaggerDocumentHelper.GetDeprecatedReasons(x)
                });
            });

            return(parameterList);
        }
        private IList <Parameter> CreateQueryParameters()
        {
            var parameterList = new List <Parameter>
            {
                new Parameter {
                    @ref = SwaggerDocumentHelper.GetParameterReference("offset")
                },
                new Parameter {
                    @ref = SwaggerDocumentHelper.GetParameterReference("limit")
                }
            };

            if (ChangeQueryFeature.IsEnabled)
            {
                parameterList.Add(
                    new Parameter {
                    @ref = SwaggerDocumentHelper.GetParameterReference("MinChangeVersion")
                });

                parameterList.Add(
                    new Parameter {
                    @ref = SwaggerDocumentHelper.GetParameterReference("MaxChangeVersion")
                });
            }

            if (_swaggerPathsFactorySelectorStrategy.HasTotalCount)
            {
                parameterList.Add(
                    new Parameter {
                    @ref = SwaggerDocumentHelper.GetParameterReference("totalCount")
                });
            }

            return(parameterList);
        }
Exemple #4
0
        private Schema CreateResourceChildSchema(ResourceChildItem resourceChildItem, SwaggerResource swaggerResource)
        {
            var properties = resourceChildItem.Properties
                             .Select(
                p => new
            {
                IsRequired = p.IsIdentifying || !p.PropertyType.IsNullable,
                Key        = UniqueIdSpecification.GetUniqueIdPropertyName(p.JsonPropertyName).ToCamelCase(),
                Schema     = SwaggerDocumentHelper.CreatePropertySchema(p)
            }).Concat(
                resourceChildItem.References.Select(
                    r => new
            {
                r.IsRequired,
                Key    = r.PropertyName.ToCamelCase(),
                Schema = new Schema
                {
                    @ref = SwaggerDocumentHelper.GetDefinitionReference(
                        _swaggerDefinitionsFactoryNamingStrategy.GetReferenceName(swaggerResource.Resource, r))
                }
            })).Concat(
                resourceChildItem.Collections.Select(
                    c => new
            {
                IsRequired = c.Association.IsRequiredCollection,
                Key        = c.JsonPropertyName,
                Schema     = CreateCollectionSchema(c, swaggerResource)
            })).Concat(
                resourceChildItem.EmbeddedObjects.Select(
                    e => new
            {
                IsRequired = false,
                Key        = e.JsonPropertyName,
                Schema     = CreateEmbeddedObjectSchema(e, swaggerResource)
            })).ToList();

            var bridgeSchema = GetEdFiExtensionBridgeReferenceSchema(resourceChildItem, swaggerResource);

            if (bridgeSchema != null)
            {
                properties.Add(
                    new
                {
                    IsRequired = false,
                    Key        = ExtensionCollectionKey,
                    Schema     = bridgeSchema
                });
            }

            var requiredProperties = properties.Where(x => x.IsRequired).Select(x => x.Key).ToList();

            return(new Schema
            {
                type = "object",
                required = requiredProperties.Any()
                    ? requiredProperties
                    : null,
                properties = properties.ToDictionary(k => k.Key, v => v.Schema)
            });
        }
        public string Create(IOpenApiMetadataResourceStrategy resourceStrategy)
        {
            try
            {
                var resources = resourceStrategy.GetFilteredResources(_documentContext)
                                .ToList();

                var swaggerDocument = new SwaggerDocument
                {
                    info = new Info
                    {
                        title       = "Ed-Fi Operational Data Store API", version = $"{ApiVersionConstants.Ods}",
                        description =
                            "The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. \n***\n > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reasonable safeguards against cross-site scripting attacks and other malicious content, but the platform does not and cannot guarantee that the data it contains is free of all potentially harmful content.* \n***\n"
                    },
                    host = "%HOST%", basePath = "%BASE_PATH%", securityDefinitions =
                        new Dictionary <string, SecurityScheme>
                    {
                        {
                            "oauth2_client_credentials", new SecurityScheme
                            {
                                type = "oauth2", description =
                                    "Ed-Fi ODS/API OAuth 2.0 Client Credentials Grant Type authorization",
                                flow   = "application", tokenUrl = "%TOKEN_URL%",
                                scopes = new Dictionary <string, string>()
                            }
                        }
                    },
                    security =
                        new List <IDictionary <string, IEnumerable <string> > >
                    {
                        new Dictionary <string, IEnumerable <string> >
                        {
                            {
                                "oauth2_client_credentials", new string[0]
                            }
                        }
                    },
                    consumes = _documentContext.IsCompositeContext
                                              ? null
                                              : SwaggerDocumentHelper.GetConsumes(),
                    produces = SwaggerDocumentHelper.GetProduces(), tags = _tagsFactory.Create(resources),
                    paths = _pathsFactory.Create(resources), definitions = _definitionsFactory.Create(resources),
                    parameters = _parametersFactory.Create(_documentContext.IsCompositeContext), responses = _responsesFactory.Create()
                };

                return(JsonConvert.SerializeObject(
                           swaggerDocument,
                           new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw;
            }
        }
Exemple #6
0
 private Schema CreateEmbeddedObjectSchema(EmbeddedObject embeddedObject, SwaggerResource swaggerResource)
 {
     return(new Schema
     {
         @ref = SwaggerDocumentHelper.GetDefinitionReference(
             _swaggerDefinitionsFactoryNamingStrategy.GetEmbeddedObjectReferenceName(swaggerResource, embeddedObject))
     });
 }
        private IList <Parameter> CreatePutParameters(SwaggerPathsResource swaggerResource)
        {
            IList <Parameter> parameterList = new List <Parameter>();

            parameterList.Add(SwaggerDocumentHelper.CreateIdParameter());

            parameterList.Add(CreateIfMatchParameter("PUT from updating"));
            parameterList.Add(CreateBodyParameter(swaggerResource));

            return(parameterList);
        }
Exemple #8
0
 public IList <Tag> Create(IEnumerable <SwaggerResource> swaggerResources)
 {
     return(swaggerResources.Where(x => _filterStrategy.ShouldInclude(x.Resource))
            .Select(
                x => new Tag
     {
         name = SwaggerDocumentHelper.GetResourcePluralName(x.Resource)
                .ToCamelCase(),
         description = x.Description
     })
            .GroupBy(t => t.name)
            .Select(g => g.First())
            .OrderBy(x => x.name)
            .ToList());
 }
        public IDictionary <string, PathItem> Create(IList <SwaggerResource> swaggerResources)
        {
            return(_swaggerPathsFactorySelectorStrategy
                   .ApplyStrategy(swaggerResources)
                   .Where(r => r.Readable || r.Writable)
                   .OrderBy(r => r.Name)
                   .SelectMany(
                       r =>
            {
                var resourceName = string.IsNullOrWhiteSpace(r.Path)
                            ? $"/{SwaggerDocumentHelper.GetResourcePluralName(r.Resource).ToCamelCase()}"
                            : r.Path;

                var resourcePath = $"/{r.ResourceSchema}{resourceName}";

                var paths = new[]
                {
                    r.SupportsAccessNonIdAccessOperations
                                ? new
                    {
                        Path = resourcePath,
                        PathItem = CreatePathItemForNonIdAccessedOperations(r)
                    }
                                : null,
                    r.SupportsIdAccessOperations
                                ? new
                    {
                        Path = $"{resourcePath}/{{id}}",
                        PathItem = CreatePathItemForAccessByIdsOperations(r)
                    }
                                : null,
                    ChangeQueryFeature.IsEnabled && !r.Name.Equals(ChangeQueryFeature.SchoolYearTypesResourceName)
                                ? new
                    {
                        Path = $"{resourcePath}/deletes",
                        PathItem = CreatePathItemForChangeQueryOperation(r)
                    }
                                : null
                };

                return paths.Where(p => p != null);
            })
                   .GroupBy(p => p.Path)
                   .Select(p => p.First())
                   .ToDictionary(p => p.Path, p => p.PathItem));
        }
Exemple #10
0
        public IDictionary <string, Schema> Create(IList <SwaggerResource> swaggerResources)
        {
            var definitions = BoilerPlateDefinitions();

            swaggerResources.Where(x => _swaggerFactoryResourceFilterStrategy.ShouldInclude(x.Resource)).Select(
                r => new
            {
                key    = _swaggerDefinitionsFactoryNamingStrategy.GetResourceName(r.Resource, r),
                schema = CreateResourceSchema(r)
            }).GroupBy(d => d?.key).Select(g => g.First()).ForEach(
                d =>
            {
                if (d != null)
                {
                    definitions.Add(d.key, d.schema);
                }
            });

            swaggerResources.SelectMany(
                r => r.Resource.AllContainedItemTypes.Where(x => _swaggerFactoryResourceFilterStrategy.ShouldInclude(x))
                .Select(
                    i => new
            {
                key    = _swaggerDefinitionsFactoryNamingStrategy.GetContainedItemTypeName(r, i),
                schema = CreateResourceChildSchema(i, r)
            }).Concat(
                    swaggerResources.SelectMany(s => s.Resource.AllContainedReferences).Select(
                        reference => new
            {
                key    = _swaggerDefinitionsFactoryNamingStrategy.GetReferenceName(r.Resource, reference),
                schema = SwaggerDocumentHelper.CreateReferenceSchema(reference)
            }))).GroupBy(d => d?.key).Select(g => g.First()).ForEach(
                d =>
            {
                if (d != null)
                {
                    definitions.Add(d.key, d.schema);
                }
            });

            _definitionsFactoryEntityExtensionStrategy.GetEdFiExtensionBridgeDefinitions(swaggerResources)
            .ForEach(pair => definitions.Add(pair.Key, pair.Value));

            return(new SortedDictionary <string, Schema>(definitions));
        }
        private Parameter CreateBodyParameter(SwaggerPathsResource swaggerPathsResource)
        {
            var camelCaseName = swaggerPathsResource.Resource.Name.ToCamelCase();

            var referenceName =
                _pathsFactoryNamingStrategy.GetResourceName(swaggerPathsResource, ContentTypeUsage.Writable);

            return(new Parameter
            {
                name = camelCaseName,
                description =
                    $"The JSON representation of the \"{camelCaseName}\" resource to be created or updated.",
                @in = "body",
                required = true,
                schema = new Schema {
                    @ref = SwaggerDocumentHelper.GetDefinitionReference(referenceName)
                }
            });
        }
 private Operation CreatePostOperation(SwaggerPathsResource swaggerResource)
 {
     return(new Operation
     {
         tags = new List <string>
         {
             SwaggerDocumentHelper.GetResourcePluralName(swaggerResource.Resource)
             .ToCamelCase()
         },
         summary = "Creates or updates resources based on the natural key values of the supplied resource.",
         description =
             "The POST operation can be used to create or update resources. In database terms, this is often referred to as an \"upsert\" operation (insert + update). Clients should NOT include the resource \"id\" in the JSON body because it will result in an error (you must use a PUT operation to update a resource by \"id\"). The web service will identify whether the resource already exists based on the natural key values provided, and update or create the resource appropriately.",
         operationId = "post" + swaggerResource.Name,
         deprecated = swaggerResource.IsDeprecated,
         consumes = new[] { _contentTypeStrategy.GetOperationContentType(swaggerResource, ContentTypeUsage.Writable) },
         parameters = CreatePostParameters(swaggerResource),
         responses = SwaggerDocumentHelper.GetWriteOperationResponses(HttpMethod.Post)
     });
 }
 private Operation CreatePutByIdOperation(SwaggerPathsResource swaggerResource)
 {
     return(new Operation
     {
         tags = new List <string>
         {
             SwaggerDocumentHelper.GetResourcePluralName(swaggerResource.Resource)
             .ToCamelCase()
         },
         summary = "Updates or creates a resource based on the resource identifier.",
         description =
             "The PUT operation is used to update or create a resource by identifier. If the resource doesn't exist, the resource will be created using that identifier. Additionally, natural key values cannot be changed using this operation, and will not be modified in the database.  If the resource \"id\" is provided in the JSON body, it will be ignored as well.",
         operationId = $"put{swaggerResource.Name}",
         deprecated = swaggerResource.IsDeprecated,
         consumes = new[] { _contentTypeStrategy.GetOperationContentType(swaggerResource, ContentTypeUsage.Writable) },
         parameters = CreatePutParameters(swaggerResource),
         responses = SwaggerDocumentHelper.GetWriteOperationResponses(HttpMethod.Put)
     });
 }
        private Operation CreateGetOperation(SwaggerPathsResource swaggerResource)
        {
            var operation = new Operation
            {
                tags = new List <string>
                {
                    SwaggerDocumentHelper.GetResourcePluralName(swaggerResource.Resource)
                    .ToCamelCase()
                },
                summary     = "Retrieves specific resources using the resource's property values (using the \"Get\" pattern).",
                description =
                    "This GET operation provides access to resources using the \"Get\" search pattern.  The values of any properties of the resource that are specified will be used to return all matching results (if it exists).",
                operationId = swaggerResource.OperationId ?? $"get{swaggerResource.Resource.PluralName}",
                deprecated  = swaggerResource.IsDeprecated,
                produces    = new[] { _contentTypeStrategy.GetOperationContentType(swaggerResource, ContentTypeUsage.Readable) },
                parameters  = CreateGetByExampleParameters(swaggerResource),
                responses   = SwaggerDocumentHelper.GetReadOperationResponses(
                    _pathsFactoryNamingStrategy.GetResourceName(swaggerResource, ContentTypeUsage.Readable), true)
            };

            return(operation);
        }
 private Operation CreateDeletesOperation(SwaggerPathsResource swaggerResource)
 {
     return(new Operation
     {
         tags = new List <string>
         {
             SwaggerDocumentHelper.GetResourcePluralName(swaggerResource.Resource)
             .ToCamelCase()
         },
         summary = "Retrieves deleted resources based on change version.",
         description = "The DELETES operation is used to retrieve deleted resources.",
         operationId = $"deletes{swaggerResource.Resource.PluralName}",
         deprecated = swaggerResource.IsDeprecated,
         consumes = new[]
         {
             _contentTypeStrategy.GetOperationContentType(
                 swaggerResource,
                 ContentTypeUsage.Writable)
         },
         parameters = new List <Parameter>
         {
             new Parameter {
                 @ref = SwaggerDocumentHelper.GetParameterReference("offset")
             },
             new Parameter {
                 @ref = SwaggerDocumentHelper.GetParameterReference("limit")
             },
             new Parameter {
                 @ref = SwaggerDocumentHelper.GetParameterReference("MinChangeVersion")
             },
             new Parameter {
                 @ref = SwaggerDocumentHelper.GetParameterReference("MaxChangeVersion")
             }
         },
         responses = SwaggerDocumentHelper.GetReadOperationResponses(
             _pathsFactoryNamingStrategy.GetResourceName(swaggerResource, ContentTypeUsage.Readable), true)
     });
 }
 private Operation CreateDeleteByIdOperation(SwaggerPathsResource swaggerResource)
 {
     return(new Operation
     {
         tags = new List <string>
         {
             SwaggerDocumentHelper.GetResourcePluralName(swaggerResource.Resource)
             .ToCamelCase()
         },
         summary = "Deletes an existing resource using the resource identifier.",
         description =
             "The DELETE operation is used to delete an existing resource by identifier. If the resource doesn't exist, an error will result (the resource will not be found).",
         operationId = $"delete{swaggerResource.Name}ById",
         deprecated = swaggerResource.IsDeprecated,
         consumes = new[] { _contentTypeStrategy.GetOperationContentType(swaggerResource, ContentTypeUsage.Writable) },
         parameters = new[]
         {
             SwaggerDocumentHelper.CreateIdParameter(),
             CreateIfMatchParameter("DELETE from removing")
         },
         responses = SwaggerDocumentHelper.GetWriteOperationResponses(HttpMethod.Delete)
     });
 }
Exemple #17
0
 private static Schema RefSchema(string referenceName)
 => new Schema
 {
     @ref = SwaggerDocumentHelper.GetDefinitionReference(referenceName)
 };
Exemple #18
0
        private Schema CreateResourceSchema(SwaggerResource swaggerResource)
        {
            var resource = swaggerResource.Resource;

            var properties = resource.UnifiedKeyAllProperties()
                             .Select(
                x => new PropertySchemaInfo
            {
                PropertyName = x.JsonPropertyName,
                IsRequired   = !x.PropertyType.IsNullable && !x.IsServerAssigned,
                Sort         = SortOrder(x.PropertyName, x.IsIdentifying),
                Schema       = SwaggerDocumentHelper.CreatePropertySchema(x)
            }).Concat(
                resource.Collections.Select(
                    x => new PropertySchemaInfo
            {
                PropertyName = CreateCollectionKey(x),
                IsRequired   = x.Association.IsRequiredCollection,
                Sort         = SortOrder(x.PropertyName, x.Association.IsRequiredCollection),
                Schema       = CreateCollectionSchema(x, swaggerResource)
            })).Concat(
                resource.EmbeddedObjects.Select(
                    x => new PropertySchemaInfo
            {
                PropertyName = x.JsonPropertyName,
                Sort         = SortOrder(x.PropertyName, false),
                Schema       = CreateEmbeddedObjectSchema(x, swaggerResource)
            })).Concat(
                resource.References.Select(
                    x => new PropertySchemaInfo
            {
                PropertyName = x.PropertyName,
                IsRequired   = x.IsRequired,
                IsReference  = true,
                Sort         = 3,
                Schema       = new Schema
                {
                    @ref = SwaggerDocumentHelper.GetDefinitionReference(
                        _swaggerDefinitionsFactoryNamingStrategy.GetReferenceName(swaggerResource.Resource, x))
                }

                // NOTE: currently there is an open issue with swagger-ui to address
                // objects showing up in the ui that have a reference and
                // other properties within the schema. The standard at this time does
                // not support this use case. (The error we get is:
                // Sibling values are not allowed along side $refs.
                // As of swagger-ui 3.11.0 this has not been resolved.
                // https://github.com/OAI/OpenAPI-Specification/issues/556
                // TODO: JSM - Once the standard is updated to accept sibling values along
                // side with $refs, uncomment the line below
                // isIdentity = x.Association.IsIdentifying ? true : (bool?) null
            })).Distinct(new PropertySchemaInfoComparer()).ToList();

            var propertyDict = properties.OrderBy(x => x.Sort).ThenBy(x => x.PropertyName)
                               .ToDictionary(x => x.PropertyName.ToCamelCase(), x => x.Schema);

            propertyDict.Add("_etag", EtagSchema);
            var bridgeSchema = GetEdFiExtensionBridgeReferenceSchema(resource, swaggerResource);

            if (bridgeSchema != null)
            {
                propertyDict.Add(ExtensionCollectionKey, bridgeSchema);
            }

            var requiredProperties = properties
                                     .Where(x => x.IsRequired && !x.PropertyName.EqualsIgnoreCase("id"))
                                     .Select(x => x.PropertyName.ToCamelCase()).ToList();

            return(new Schema
            {
                type = "object",
                required = requiredProperties.Any()
                    ? requiredProperties
                    : null,
                properties = propertyDict
            });
        }