Ejemplo n.º 1
0
        /// <summary>Generates the Swagger specification.</summary>
        /// <param name="context">The context.</param>
        /// <returns>The Swagger specification.</returns>
        protected virtual async Task <string> GenerateSwaggerAsync(IOwinContext context)
        {
            if (_schemaException != null && _schemaTimestamp + _settings.ExceptionCacheTime > DateTimeOffset.UtcNow)
            {
                throw _schemaException;
            }

            if (_schemaJson == null)
            {
                try
                {
                    var settings  = _settings.CreateGeneratorSettings(null);
                    var generator = new WebApiToSwaggerGenerator(settings, _schemaGenerator);
                    var document  = await generator.GenerateForControllersAsync(_controllerTypes);

                    document.Host = context.Request.Host.Value ?? "";
                    document.Schemes.Add(context.Request.Scheme == "http" ? SwaggerSchema.Http : SwaggerSchema.Https);
                    document.BasePath = context.Request.PathBase.Value?.Substring(0, context.Request.PathBase.Value.Length - (_settings.MiddlewareBasePath?.Length ?? 0)) ?? "";

                    _settings.PostProcess?.Invoke(document);
                    _schemaJson      = document.ToJson();
                    _schemaException = null;
                    _schemaTimestamp = DateTimeOffset.UtcNow;
                }
                catch (Exception exception)
                {
                    _schemaJson      = null;
                    _schemaException = exception;
                    _schemaTimestamp = DateTimeOffset.UtcNow;
                    throw _schemaException;
                }
            }

            return(_schemaJson);
        }
Ejemplo n.º 2
0
        private async Task <SwaggerDocument> GetSwaggerDocument()
        {
            // Workaround: NSwag semm to have a bug in enum handling
            void editEnumType(JsonSchema4 type)
            {
                if (type.IsEnumeration && type.Type == JsonObjectType.None)
                {
                    type.Type = JsonObjectType.Integer;
                }
                foreach (var t in type.Properties.Values)
                {
                    editEnumType(t);
                }
            }

            // var d = await SwaggerDocument.FromFileAsync("c:/users/exyi/Downloads/github-swagger.json");



            var settings  = new WebApiToSwaggerGeneratorSettings();
            var generator = new WebApiToSwaggerGenerator(settings);

            var controllers = typeof(GeneratorViewModel)
                              .GetTypeInfo()
                              .Assembly.GetTypes()
                              .Where(t => typeof(Controller).IsAssignableFrom(t));
            var d = await generator.GenerateForControllersAsync(controllers);

            this.PopulateOperationIds(d);
            foreach (var t in d.Definitions.Values)
            {
                editEnumType(t);
            }
            return(d);
        }
        public async Task When_operations_have_no_tags_they_are_grouped_into_one_client()
        {
            //// Arrange
            var generator = new WebApiToSwaggerGenerator(new WebApiToSwaggerGeneratorSettings());
            var document  = await generator.GenerateForControllersAsync(new List <Type>() { typeof(PointControllerA), typeof(PointControllerB) });

            // Remove tags
            foreach (var path in document.Paths.Values)
            {
                foreach (var operation in path.Values)
                {
                    operation.Tags.Clear();
                }
            }
            var codeGenerator = new SwaggerToTypeScriptClientGenerator(document, new SwaggerToTypeScriptClientGeneratorSettings
            {
                OperationNameGenerator = new MultipleClientsFromFirstTagAndPathSegmentsOperationNameGenerator()
            });

            //// Act
            var code = codeGenerator.GenerateFile();

            //// Assert
            Assert.IsTrue(code.Contains("export class Client"));
            Assert.IsTrue(!code.Contains("export class PointControllerAClient"));
            Assert.IsTrue(!code.Contains("export class PointControllerBClient"));
        }
Ejemplo n.º 4
0
        /// <summary>Generates the Swagger specification.</summary>
        /// <param name="context">The context.</param>
        /// <returns>The Swagger specification.</returns>
        protected virtual async Task <string> GenerateSwaggerAsync(HttpContext context)
        {
            if (_swaggerJson == null)
            {
                if (_swaggerJson == null)
                {
                    try
                    {
                        var generator = new WebApiToSwaggerGenerator(_settings, _schemaGenerator);
                        var document  = await generator.GenerateForControllersAsync(_controllerTypes);

                        document.Host = context.Request.Host.Value ?? "";
                        document.Schemes.Add(context.Request.Scheme == "http" ? SwaggerSchema.Http : SwaggerSchema.Https);
                        document.BasePath = context.Request.PathBase.Value?.Substring(0, context.Request.PathBase.Value.Length - (_settings.MiddlewareBasePath?.Length ?? 0)) ?? "";

                        _settings.PostProcess?.Invoke(document);
                        _swaggerJson = document.ToJson();
                    }
                    catch (Exception exception)
                    {
                        _swaggerJson = exception.ToString();
                    }
                }
            }

            return(_swaggerJson);
        }
Ejemplo n.º 5
0
        private async Task <SwaggerDocument> GetSwaggerDocument()
        {
            var settings  = new WebApiToSwaggerGeneratorSettings();
            var generator = new WebApiToSwaggerGenerator(settings);

            var controllers = typeof(GeneratorViewModel)
                              .GetTypeInfo()
                              .Assembly.GetTypes()
                              .Where(t => typeof(Controller).IsAssignableFrom(t));

            return(await generator.GenerateForControllersAsync(controllers));
        }
Ejemplo n.º 6
0
        protected override async Task <string> RunIsolatedAsync(AssemblyLoader.AssemblyLoader assemblyLoader)
        {
            await TransformAsync(assemblyLoader);

            var controllerNames = ControllerNames.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();

            if (!controllerNames.Any() && AssemblyPaths?.Length > 0)
            {
                controllerNames = GetControllerNames(assemblyLoader).ToList();
            }

            var controllerTypes = await GetControllerTypesAsync(controllerNames, assemblyLoader);

            var generator = new WebApiToSwaggerGenerator(Settings);
            var document  = await generator.GenerateForControllersAsync(controllerTypes).ConfigureAwait(false);

            if (ServiceHost == ".")
            {
                document.Host = string.Empty;
            }
            else if (!string.IsNullOrEmpty(ServiceHost))
            {
                document.Host = ServiceHost;
            }

            if (string.IsNullOrEmpty(DocumentTemplate))
            {
                if (!string.IsNullOrEmpty(InfoTitle))
                {
                    document.Info.Title = InfoTitle;
                }
                if (!string.IsNullOrEmpty(InfoVersion))
                {
                    document.Info.Version = InfoVersion;
                }
                if (!string.IsNullOrEmpty(InfoDescription))
                {
                    document.Info.Description = InfoDescription;
                }
            }

            if (ServiceSchemes != null && ServiceSchemes.Any())
            {
                document.Schemes = ServiceSchemes.Select(s => (SwaggerSchema)Enum.Parse(typeof(SwaggerSchema), s, true)).ToList();
            }

            if (!string.IsNullOrEmpty(ServiceBasePath))
            {
                document.BasePath = ServiceBasePath;
            }

            return(document.ToJson());
        }
Ejemplo n.º 7
0
        public async Task GenerateSwagger()
        {
            var settings  = new WebApiToSwaggerGeneratorSettings();
            var generator = new WebApiToSwaggerGenerator(settings);

            var controllers = typeof(GeneratorViewModel)
                              .GetTypeInfo()
                              .Assembly.GetTypes()
                              .Where(t => typeof(Controller).IsAssignableFrom(t));
            var d = await generator.GenerateForControllersAsync(controllers);

            Context.ReturnFile(Encoding.UTF8.GetBytes(d.ToJson()), "WebApi.swagger.json", "text/json");
        }
Ejemplo n.º 8
0
        private async Task <SwaggerDocument> GetSwaggerDocument()
        {
            return(await SwaggerDocument.FromFileAsync("c:/users/exyi/Downloads/github-swagger.json"));

            var settings  = new WebApiToSwaggerGeneratorSettings();
            var generator = new WebApiToSwaggerGenerator(settings);

            var controllers = typeof(GeneratorViewModel)
                              .GetTypeInfo()
                              .Assembly.GetTypes()
                              .Where(t => typeof(Controller).IsAssignableFrom(t));

            return(await generator.GenerateForControllersAsync(controllers));
        }
Ejemplo n.º 9
0
        /// <summary>Generates the Swagger specification.</summary>
        /// <param name="context">The context.</param>
        /// <returns>The Swagger specification.</returns>
        protected virtual async Task <string> GenerateSwaggerAsync(HttpContext context)
        {
            if (_schemaException != null && _schemaTimestamp + _settings.ExceptionCacheTime > DateTimeOffset.UtcNow)
            {
                throw _schemaException;
            }

            if (_schemaJson == null)
            {
                if (_schemaJson == null)
                {
                    try
                    {
                        // TODO: Move to NJS (same in other generator)
                        var isSerializerSettingsSpecified =
                            _settings.GeneratorSettings.DefaultPropertyNameHandling != PropertyNameHandling.Default ||
                            _settings.GeneratorSettings.DefaultEnumHandling != EnumHandling.Integer ||
                            _settings.GeneratorSettings.ContractResolver != null |
                            _settings.GeneratorSettings.SerializerSettings != null;

                        if (!isSerializerSettingsSpecified)
                        {
                            _settings.GeneratorSettings.SerializerSettings = _mvcJsonOptions.Value.SerializerSettings;
                        }

                        var generator = new WebApiToSwaggerGenerator(_settings.GeneratorSettings, _schemaGenerator);
                        var document  = await generator.GenerateForControllersAsync(_controllerTypes);

                        document.Host = context.Request.Host.Value ?? "";
                        document.Schemes.Add(context.Request.Scheme == "http" ? SwaggerSchema.Http : SwaggerSchema.Https);
                        document.BasePath = context.Request.PathBase.Value?.Substring(0, context.Request.PathBase.Value.Length - (_settings.MiddlewareBasePath?.Length ?? 0)) ?? "";

                        _settings.PostProcess?.Invoke(document);
                        _schemaJson      = document.ToJson();
                        _schemaException = null;
                        _schemaTimestamp = DateTimeOffset.UtcNow;
                    }
                    catch (Exception exception)
                    {
                        _schemaJson      = null;
                        _schemaException = exception;
                        _schemaTimestamp = DateTimeOffset.UtcNow;
                        throw _schemaException;
                    }
                }
            }

            return(_schemaJson);
        }
Ejemplo n.º 10
0
        /// <summary>Generates the Swagger specification.</summary>
        /// <param name="context">The context.</param>
        /// <returns>The Swagger specification.</returns>
        protected virtual async Task <string> GenerateDocumentAsync(IOwinContext context)
        {
            var settings  = _settings.CreateGeneratorSettings(null, null);
            var generator = new WebApiToSwaggerGenerator(settings, _schemaGenerator);
            var document  = await generator.GenerateForControllersAsync(_controllerTypes);

            document.Host = context.Request.Host.Value ?? "";
            document.Schemes.Add(context.Request.Scheme == "http" ? SwaggerSchema.Http : SwaggerSchema.Https);
            document.BasePath = context.Request.PathBase.Value?.Substring(0, context.Request.PathBase.Value.Length - (_settings.MiddlewareBasePath?.Length ?? 0)) ?? "";

            _settings.PostProcess?.Invoke(document);
            var schemaJson = document.ToJson();

            return(schemaJson);
        }
        public async Task When_operations_have_different_tags_they_are_grouped_into_different_clients()
        {
            //// Arrange
            var generator = new WebApiToSwaggerGenerator(new WebApiToSwaggerGeneratorSettings());
            var document  = await generator.GenerateForControllersAsync(new List <Type>() { typeof(PointControllerA), typeof(PointControllerB) });

            var codeGenerator = new SwaggerToTypeScriptClientGenerator(document, new SwaggerToTypeScriptClientGeneratorSettings
            {
                OperationNameGenerator = new MultipleClientsFromFirstTagAndPathSegmentsOperationNameGenerator()
            });

            //// Act
            var code = codeGenerator.GenerateFile();

            //// Assert
            Assert.IsTrue(code.Contains("export class PointControllerAClient"));
            Assert.IsTrue(code.Contains("export class PointControllerBClient"));
        }
Ejemplo n.º 12
0
        public async Task When_there_are_duplicate_paths_through_inheritance_then_the_base_method_is_ignored()
        {
            //// Arrange
            var generator = new WebApiToSwaggerGenerator(new WebApiToSwaggerGeneratorSettings());

            //// Act
            var document = await generator.GenerateForControllersAsync(new Type[] { typeof(StandardController), typeof(SpecificController) });

            var json = document.ToJson();

            //// Assert
            Assert.AreEqual(4, document.Operations.Count());

            Assert.IsTrue(document.Operations.Any(o => o.Path == "/api/common/standard/export"));
            Assert.IsTrue(document.Operations.Any(o => o.Path == "/api/common/standard/foo"));

            Assert.IsTrue(document.Operations.Any(o => o.Path == "/api/whatever/specific/export"));
            Assert.IsTrue(document.Operations.Any(o => o.Path == "/api/whatever/specific/foo"));
        }
Ejemplo n.º 13
0
        public async Task When_IncludedVersions_are_set_then_only_these_are_available_in_document()
        {
            //// Arrange
            var settings = new WebApiToSwaggerGeneratorSettings();

            settings.OperationProcessors.Get <ApiVersionProcessor>().IncludedVersions.Add("1");

            var generator = new WebApiToSwaggerGenerator(settings);

            //// Act
            var document = await generator.GenerateForControllersAsync(new List <Type>
            {
                typeof(VersionedControllerV1),
                typeof(VersionedControllerV2)
            });

            //// Assert
            Assert.AreEqual(2, document.Paths.Count);

            Assert.IsTrue(document.Paths.ContainsKey("/api/v1/foo"));
            Assert.IsTrue(document.Paths.ContainsKey("/api/v1/bar"));
        }
Ejemplo n.º 14
0
        public async Task When_no_IncludedVersions_are_defined_then_all_routes_are_available_and_replaced()
        {
            //// Arrange
            var settings  = new WebApiToSwaggerGeneratorSettings();
            var generator = new WebApiToSwaggerGenerator(settings);

            //// Act
            var document = await generator.GenerateForControllersAsync(new List <Type>
            {
                typeof(VersionedControllerV1),
                typeof(VersionedControllerV2)
            });

            //// Assert
            Assert.AreEqual(4, document.Paths.Count);

            Assert.IsTrue(document.Paths.ContainsKey("/api/v1/foo"));
            Assert.IsTrue(document.Paths.ContainsKey("/api/v1/bar"));

            Assert.IsTrue(document.Paths.ContainsKey("/api/v2/foo"));
            Assert.IsTrue(document.Paths.ContainsKey("/api/v2/bar"));
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            var controllers = Metadata.GetAllControllers();

            var swagDocSettings = new WebApiToSwaggerGeneratorSettings
            {
                DefaultUrlTemplate = "api/{controller}/{action}/{id}"
            };
            var swagDocGenerator = new WebApiToSwaggerGenerator(swagDocSettings);
            var document         = swagDocGenerator.GenerateForControllersAsync(controllers).Result;

            var codeGenSettings = new SwaggerToTypeScriptClientGeneratorSettings
            {
                Template    = TypeScriptTemplate.Fetch,
                PromiseType = PromiseType.Promise,
                GenerateClientInterfaces = true
            };

            var generator = new SwaggerToTypeScriptClientGenerator(document, codeGenSettings);
            var code      = generator.GenerateFile();

            code = code.RemoveStatusCodeHandling();
            code = code.AddReferencedTypes();
            code = code.WithCustomReplacements();

            string outputPath = string.Empty;

            var directory = ConfigurationManager.AppSettings["OutputDirectory"].ToString();

            directory = directory.EndsWith("\\", System.StringComparison.InvariantCultureIgnoreCase) ? directory : directory + "\\";
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            outputPath = directory + "ApiClient.ts";

            File.WriteAllText(outputPath, code);
        }