public static void UseGeneratedClient(this IApplicationBuilder app, string url) { Task.Run(() => { Thread.Sleep(2000); SwaggerDocument document = null; int attemptCount = 0; while (document == null && attemptCount < 5) { attemptCount++; System.Console.WriteLine("Attempting to load swagger specification for client generation."); try { document = SwaggerDocument.FromUrlAsync(url).Result; } catch { System.Console.WriteLine("Failed to load swagger specification. Retry in 2 seconds."); Thread.Sleep(2000); } } var settings = new SwaggerToTypeScriptClientGeneratorSettings { Template = TypeScriptTemplate.Angular, ClassName = "{controller}Client", InjectionTokenType = InjectionTokenType.InjectionToken }; var generator = new SwaggerToTypeScriptClientGenerator(document, settings); var code = generator.GenerateFile(); System.Console.WriteLine(code); System.IO.File.WriteAllText(@"./ClientApp/src/app/app.service.ts", code); }); }
static void Main(string[] args) { var currentFolder = Directory.GetCurrentDirectory(); var pathToDll = Path.Combine(currentFolder, "..", "ContactsList/bin/Debug/netcoreapp1.1/AspNetCoreSpa.dll"); var settings = new WebApiAssemblyToSwaggerGeneratorSettings { AssemblyPaths = new string[] { pathToDll }, DefaultUrlTemplate = "api/{controller}/{action}/{id}", DefaultPropertyNameHandling = NJsonSchema.PropertyNameHandling.CamelCase }; //var excluded = new string[] { "Manage", "Base", "Home" }; var generator = new WebApiAssemblyToSwaggerGenerator(settings); var allClasses = generator.GetControllerClasses(); //var necessaryClasses = allClasses.Except(allClasses.Where(x => excluded.Any(y => x.Contains(y))) // ).ToArray(); var controllersToGenerate = new string[] { "File" }; var necessaryClasses = allClasses.Where(x => controllersToGenerate.Any(y => x.Contains(y))) .ToArray(); var document = generator.GenerateForControllersAsync(necessaryClasses).Result; var settingsForClientApiGeneration = new SwaggerToTypeScriptClientGeneratorSettings { ClassName = "{controller}Client", Template = TypeScriptTemplate.Angular }; var generatorApi = new SwaggerToTypeScriptClientGenerator(document, settingsForClientApiGeneration); var code = generatorApi.GenerateFile(); code = ImproveGeneration(code); File.WriteAllText(Path.Combine(currentFolder, "..", "ContactsList/Client/app", "apiDefinitions.ts"), code); }
public static void GenerateTS(SwaggerDocument document, ApiClientDefinition definition) { var settings = new SwaggerToTypeScriptClientGeneratorSettings() { Template = TypeScriptTemplate.Fetch, OperationNameGenerator = new CustomNameGenerator(), GenerateOptionalParameters = true, UseTransformOptionsMethod = true, ClientBaseClass = "ClientBase" }; settings.TypeScriptGeneratorSettings.PropertyNameGenerator = new MyPropertyNameGenerator(c => ConversionUtilities.ConvertToLowerCamelCase(c, true)); settings.TypeScriptGeneratorSettings.NullValue = TypeScriptNullValue.Null; var generator = new SwaggerToTypeScriptClientGenerator(document, settings); var ts = generator.GenerateFile(); var baseClass = CreateBaseClass(definition); ts = WrapInNamespace(definition, ts, baseClass); File.WriteAllText(definition.TypescriptClient, ts); if (definition.CompileTypescript) { Process.Start("tsc", definition.TypescriptClient).WaitForExit(); } }
internal TypeScriptFrameworkModel(SwaggerToTypeScriptClientGeneratorSettings settings) { _settings = settings; RxJs = new TypeScriptFrameworkRxJsModel(this); Angular = new TypeScriptFrameworkAngularModel(settings); }
/// <summary>Initializes a new instance of the <see cref="TypeScriptParameterModel" /> class.</summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="variableName">Name of the variable.</param> /// <param name="typeName">The type name.</param> /// <param name="parameter">The parameter.</param> /// <param name="allParameters">All parameters.</param> /// <param name="settings">The settings.</param> /// <param name="generator">The client generator base.</param> public TypeScriptParameterModel(string parameterName, string variableName, string typeName, SwaggerParameter parameter, IList <SwaggerParameter> allParameters, SwaggerToTypeScriptClientGeneratorSettings settings, SwaggerToTypeScriptClientGenerator generator) : base(parameterName, variableName, typeName, parameter, allParameters, settings.TypeScriptGeneratorSettings, generator, new TypeScriptValueGenerator(new TypeScriptTypeResolver(settings.TypeScriptGeneratorSettings), settings.TypeScriptGeneratorSettings)) { _settings = settings; }
/// <summary>Initializes a new instance of the <see cref="TypeScriptOperationModel" /> class.</summary> /// <param name="operation">The operation.</param> /// <param name="settings">The settings.</param> /// <param name="generator">The generator.</param> /// <param name="resolver">The resolver.</param> public TypeScriptOperationModel( SwaggerOperation operation, SwaggerToTypeScriptClientGeneratorSettings settings, SwaggerToTypeScriptClientGenerator generator, TypeResolverBase resolver) : base(null, operation, resolver, generator, settings) { _operation = operation; _settings = settings; _generator = generator; var parameters = GetActualParameters(); if (settings.GenerateOptionalParameters) { parameters = parameters .OrderBy(p => p.Position ?? 0) .OrderBy(p => !p.IsRequired) .ToList(); } Parameters = parameters .Select(parameter => new TypeScriptParameterModel(parameter.Name, GetParameterVariableName(parameter, _operation.Parameters), ResolveParameterType(parameter), parameter, parameters, _settings, _generator, resolver)) .ToList(); }
public async Task When_query_parameter_is_enum_array_then_the_enum_is_referenced() { //// Arrange var settings = new WebApiToSwaggerGeneratorSettings { DefaultUrlTemplate = "api/{controller}/{action}/{id}", DefaultEnumHandling = EnumHandling.String, DefaultPropertyNameHandling = PropertyNameHandling.Default, SchemaType = SchemaType.Swagger2, }; var generator = new WebApiToSwaggerGenerator(settings); //// Act var document = await generator.GenerateForControllerAsync <FooController>(); var json = document.ToJson(); var clientSettings = new SwaggerToTypeScriptClientGeneratorSettings { Template = TypeScriptTemplate.JQueryCallbacks }; clientSettings.TypeScriptGeneratorSettings.TypeScriptVersion = 1.8m; var gen = new SwaggerToTypeScriptClientGenerator(document, clientSettings); var code = gen.GenerateFile(); //// Assert Assert.NotNull(document.Operations.First().Operation.Parameters.First().Item.Reference); Assert.Contains("getFoos(bars: Bar[], ", code); }
static void Main(string[] args) { var swaggerSpecUrl = args.Length > 0 ? args[0] : DefaultSwaggerSpecUrl; var outputFile = args.Length > 1 ? args[1] : DefaultOutputFile; Console.WriteLine($"Swagger描述文档地址为:{swaggerSpecUrl}"); Console.WriteLine($"客户端代理类输出地址为:{Path.GetFullPath(outputFile)}"); // 配置 var document = SwaggerDocument.FromUrlAsync(swaggerSpecUrl).GetAwaiter().GetResult(); var settings = new SwaggerToTypeScriptClientGeneratorSettings { ClassName = "{controller}" + ClassNameSuffix, OperationNameGenerator = new MultipleClientsFromPathSegmentsOperationNameGenerator(), HttpClass = HttpClass.HttpClient, InjectionTokenType = InjectionTokenType.InjectionToken, ClientBaseClass = null, Template = TypeScriptTemplate.Angular }; settings.TypeScriptGeneratorSettings.DateTimeType = TypeScriptDateTimeType.Date; settings.TypeScriptGeneratorSettings.GenerateCloneMethod = true; settings.TypeScriptGeneratorSettings.ExtendedClasses = null; settings.CodeGeneratorSettings.TemplateDirectory = "Template"; // 生成客户端代理类 GenerateFile(document, settings, outputFile); Console.WriteLine("生成客户端代理类成功"); // 生成Module GenerateModule(document, settings, GetModuleFile(outputFile)); Console.WriteLine("生成模块文件成功"); }
/// <summary>Initializes a new instance of the <see cref="ClientTemplateModel" /> class.</summary> /// <param name="controllerClassName">Name of the controller.</param> /// <param name="operations">The operations.</param> /// <param name="document">The Swagger document.</param> /// <param name="settings">The settings.</param> public ClientTemplateModel(string controllerClassName, IList<OperationModel> operations, SwaggerDocument document, SwaggerToTypeScriptClientGeneratorSettings settings) { _settings = settings; _document = document; Class = controllerClassName; Operations = operations; }
/// <summary>Initializes a new instance of the <see cref="ClientTemplateModel" /> class.</summary> /// <param name="controllerClassName">Name of the controller.</param> /// <param name="operations">The operations.</param> /// <param name="document">The Swagger document.</param> /// <param name="settings">The settings.</param> public ClientTemplateModel(string controllerClassName, IList <OperationModel> operations, SwaggerDocument document, SwaggerToTypeScriptClientGeneratorSettings settings) { _settings = settings; _document = document; Class = controllerClassName; Operations = operations; }
static void GenerateFile(SwaggerDocument document, SwaggerToTypeScriptClientGeneratorSettings settings, string clientFile) { var generator = new SwaggerToTypeScriptClientGenerator(document, settings); var code = generator.GenerateFile(); using (var writer = new StreamWriter(clientFile, false, Encoding.UTF8)) { writer.Write(code); } }
static void GenerateModule(SwaggerDocument document, SwaggerToTypeScriptClientGeneratorSettings settings, string moduleFile) { // 生成Module var clients = document.Operations .Select(operation => settings.OperationNameGenerator.GetClientName(document, operation.Path, operation.Method, operation.Operation)) .Distinct() .Select(c => $"{c}{ClassNameSuffix}"); clients.RenderToFile(Path.Combine("Template", "Module.liquid"), moduleFile); }
/// <summary>Initializes a new instance of the <see cref="FileTemplateModel"/> class.</summary> /// <param name="clientCode">The client code.</param> /// <param name="clientClasses">The client classes.</param> /// <param name="settings">The settings.</param> /// <param name="resolver">The resolver.</param> public FileTemplateModel(string clientCode, IEnumerable <string> clientClasses, SwaggerToTypeScriptClientGeneratorSettings settings, TypeScriptTypeResolver resolver) { _settings = settings; _resolver = resolver; _clientCode = clientCode; ClientClasses = clientClasses.ToArray(); Types = GenerateDtoTypes(); ExtensionCodeAfter = GenerateExtensionCodeAfter(); }
public IActionResult Generate() { var settings = new WebApiToSwaggerGeneratorSettings { DefaultUrlTemplate = "api/{controller}/{action}/{id}", DefaultPropertyNameHandling = PropertyNameHandling.CamelCase }; var generator = new WebApiToSwaggerGenerator(settings); var controllers = typeof(Ng2GenerateController).GetTypeInfo().Assembly.GetTypes() .Where(t => typeof(Controller).IsAssignableFrom(t)) .ToList(); var document = generator.GenerateForControllers(controllers); //var json = document.ToJson(); //return Content(document.ToJson()); var typescriptGeneratorSettings = new SwaggerToTypeScriptClientGeneratorSettings() { ClassName = "{controller}Client", Template = TypeScriptTemplate.Angular2, GenerateClientClasses = true, GenerateClientInterfaces = true, GenerateDtoTypes = true, TypeScriptGeneratorSettings = new TypeScriptGeneratorSettings() { TypeStyle = TypeScriptTypeStyle.Interface, //TypeNameGenerator = new MyTypeNameGenerator(), } }; var tsGenerator = new SwaggerToTypeScriptClientGenerator(document, typescriptGeneratorSettings); var typescript = tsGenerator.GenerateFile(); typescript = @" // this is file generated by hitting the /swagger/ng2 endpoint " + typescript; // hack! typescript = typescript.Replace("return <Observable<any>><any>Observable.throw(e);", "return <Observable<any>><any>Observable.throw(response);"); typescript = typescript.Replace("return <Observable<UserProfileVm>><any>Observable.throw(e)", "return <Observable<any>><any>Observable.throw(response)"); // write typescript to file under ng app var webRoot = _env.WebRootPath; var file = System.IO.Path.Combine(webRoot, @"..\ClientApp\app\Right4MeClient.ts"); System.IO.File.WriteAllText(file, typescript); return(Content(typescript)); }
/// <summary>Initializes a new instance of the <see cref="FileTemplateModel" /> class.</summary> /// <param name="document">The Swagger document.</param> /// <param name="clientCode">The client code.</param> /// <param name="clientClasses">The client classes.</param> /// <param name="settings">The settings.</param> /// <param name="extensionCode">The extension code.</param> /// <param name="resolver">The resolver.</param> public FileTemplateModel(SwaggerDocument document, string clientCode, IEnumerable<string> clientClasses, SwaggerToTypeScriptClientGeneratorSettings settings, TypeScriptExtensionCode extensionCode, TypeScriptTypeResolver resolver) { _document = document; _extensionCode = extensionCode; _settings = settings; _resolver = resolver; _clientCode = clientCode; ClientClasses = clientClasses.ToArray(); Types = GenerateDtoTypes(); ExtensionCodeBottom = GenerateExtensionCodeAfter(); }
public async Task GenerateTS() { var document = await GetSwaggerDocument(); var settings = new SwaggerToTypeScriptClientGeneratorSettings() { Template = TypeScriptTemplate.Fetch }; var generator = new SwaggerToTypeScriptClientGenerator(document, settings); File.WriteAllText(TSPath, generator.GenerateFile()); }
/// <summary>Initializes a new instance of the <see cref="TypeScriptClientTemplateModel" /> class.</summary> /// <param name="controllerClassName">Name of the controller.</param> /// <param name="operations">The operations.</param> /// <param name="extensionCode">The extension code.</param> /// <param name="document">The Swagger document.</param> /// <param name="settings">The settings.</param> public TypeScriptClientTemplateModel( string controllerClassName, IEnumerable <TypeScriptOperationModel> operations, TypeScriptExtensionCode extensionCode, SwaggerDocument document, SwaggerToTypeScriptClientGeneratorSettings settings) { _extensionCode = extensionCode; _settings = settings; _document = document; Class = controllerClassName; Operations = operations; }
public async Task GenerateTS() { var document = await GetSwaggerDocument(); var settings = new SwaggerToTypeScriptClientGeneratorSettings() { Template = TypeScriptTemplate.Fetch, }; var generator = new SwaggerToTypeScriptClientGenerator(document, settings); Context.ReturnFile(Encoding.UTF8.GetBytes(generator.GenerateFile().Replace("\nexport ", "\n")), "ApiClient.ts", "text/plain"); //File.WriteAllText(TSPath, generator.GenerateFile()); }
public static void GenerateTS(SwaggerDocument document, ApiClientDefinition definition, bool promptOnFileOverwrite) { var className = Path.GetFileNameWithoutExtension(definition.TypescriptClient); var settings = new SwaggerToTypeScriptClientGeneratorSettings() { Template = TypeScriptTemplate.Fetch, OperationNameGenerator = new CustomOperationNameGenerator(), GenerateOptionalParameters = true, UseTransformOptionsMethod = true, ClientBaseClass = "ClientBase", TypeScriptGeneratorSettings = { PropertyNameGenerator = new CustomPropertyNameGenerator(c => c), NullValue = TypeScriptNullValue.Null } }; if (definition.IsSingleClient) { // set the class name only when Swagger generates one client, otherwise all classes would have the same name settings.ClassName = className; } settings.TypeScriptGeneratorSettings.TemplateFactory = new DotvvmClientTemplateFactory(settings.CodeGeneratorSettings, new[] { typeof(TypeScriptGeneratorSettings).Assembly, typeof(SwaggerToTypeScriptClientGeneratorSettings).Assembly }); var resolver = new TypeScriptTypeResolver(settings.TypeScriptGeneratorSettings); var generator = new DotvvmSwaggerToTypeScriptClientGenerator(document, settings, resolver); var ts = generator.GenerateFile(); var baseClass = definition.CreateBaseClass(); ts = definition.WrapInNamespace(ts, baseClass); FileSystemHelpers.WriteFile(definition.TypescriptClient, ts, promptOnFileOverwrite); if (definition.CompileTypescript) { Process.Start(new ProcessStartInfo() { FileName = "tsc", Arguments = definition.TypescriptClient, UseShellExecute = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }).WaitForExit(); } }
public string Gen(SwaggerDocument service, SwaggerToolSettings setting, TypeScriptTemplate Template) { var settings = new SwaggerToTypeScriptClientGeneratorSettings { ClassName = setting.TypeScriptGen.ClassName, Template = Template, PromiseType = PromiseType.Promise, TypeScriptGeneratorSettings = { ModuleName = setting.TypeScriptGen.ModuleName } }; var generator = new SwaggerToTypeScriptClientGenerator(service, settings); var code = generator.GenerateFile(); return(code); }
/// <summary>Initializes a new instance of the <see cref="TypeScriptClientTemplateModel" /> class.</summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="controllerClassName">Name of the controller.</param> /// <param name="operations">The operations.</param> /// <param name="extensionCode">The extension code.</param> /// <param name="document">The Swagger document.</param> /// <param name="settings">The settings.</param> public TypeScriptClientTemplateModel( string controllerName, string controllerClassName, IEnumerable <TypeScriptOperationModel> operations, TypeScriptExtensionCode extensionCode, SwaggerDocument document, SwaggerToTypeScriptClientGeneratorSettings settings) { _extensionCode = extensionCode; _settings = settings; _document = document; Class = controllerClassName; Operations = operations; BaseClass = _settings.ClientBaseClass?.Replace("{controller}", controllerName); Framework = new TypeScriptFrameworkModel(settings); }
/// <summary>Initializes a new instance of the <see cref="TypeScriptFileTemplateModel" /> class.</summary> /// <param name="clientCode">The client code.</param> /// <param name="clientClasses">The client classes.</param> /// <param name="document">The Swagger document.</param> /// <param name="extensionCode">The extension code.</param> /// <param name="settings">The settings.</param> /// <param name="resolver">The resolver.</param> public TypeScriptFileTemplateModel( string clientCode, IEnumerable <string> clientClasses, SwaggerDocument document, TypeScriptExtensionCode extensionCode, SwaggerToTypeScriptClientGeneratorSettings settings, TypeScriptTypeResolver resolver) { _document = document; _extensionCode = extensionCode; _settings = settings; _resolver = resolver; _clientCode = clientCode; ClientClasses = clientClasses.ToArray(); Types = GenerateDtoTypes(); ExtensionCodeBottom = GenerateExtensionCodeAfter(); }
public DotvvmTypeScriptOperationModel(SwaggerOperation operation, SwaggerToTypeScriptClientGeneratorSettings settings, SwaggerToTypeScriptClientGenerator generator, TypeResolverBase resolver) : base(operation, settings, generator, resolver) { var parameters = operation.ActualParameters.ToList(); if (settings.GenerateOptionalParameters) { parameters = parameters.OrderBy(p => !p.IsRequired).ToList(); } var newParameters = parameters.Select(parameter => new DotvvmTypeScriptParameterModel(parameter.Name, GetParameterVariableName(parameter, operation.Parameters), ResolveParameterType(parameter), parameter, parameters, settings, generator, this) ); Parameters = new List <TypeScriptParameterModel>(newParameters); }
static void Main(string[] args) { var document = SwaggerDocument.FromFileAsync("./swagger-doc.json").Result; var settings = new SwaggerToTypeScriptClientGeneratorSettings { TypeScriptGeneratorSettings = { TypeScriptVersion = 2.3m, TypeStyle = TypeScriptTypeStyle.Class, NullHandling = NullHandling.Swagger }, Template = TypeScriptTemplate.Angular }; var generator = new SwaggerToTypeScriptClientGenerator(document, settings); Console.WriteLine(generator.GenerateFile()); }
// First arg indicates what file we should save the generated code to. static void Main(string[] args) { if (args.Length != 1) { throw new Exception("Expected exactly one argument, which is the target file name of the generated TS code."); } var settings = new SwaggerToTypeScriptClientGeneratorSettings { ClassName = "SD2{controller}Api", GenerateClientInterfaces = true, Template = TypeScriptTemplate.Angular }; var swaggerDoc = Swagger.GenerateSwaggerDocument().Result; var generator = new SwaggerToTypeScriptClientGenerator(swaggerDoc, settings); var typescriptCode = generator.GenerateFile(); File.WriteAllText(args[0], typescriptCode); }
/// <summary>Initializes a new instance of the <see cref="TypeScriptFileTemplateModel" /> class.</summary> /// <param name="clientTypes">The client types.</param> /// <param name="dtoTypes">The DTO types.</param> /// <param name="document">The Swagger document.</param> /// <param name="extensionCode">The extension code.</param> /// <param name="settings">The settings.</param> /// <param name="resolver">The resolver.</param> public TypeScriptFileTemplateModel( IEnumerable <CodeArtifact> clientTypes, IEnumerable <CodeArtifact> dtoTypes, SwaggerDocument document, TypeScriptExtensionCode extensionCode, SwaggerToTypeScriptClientGeneratorSettings settings, TypeScriptTypeResolver resolver) { _document = document; _extensionCode = extensionCode; _settings = settings; _resolver = resolver; _clientCode = clientTypes.Concatenate(); _clientTypes = clientTypes; Types = dtoTypes.Concatenate(); ExtensionCodeBottom = GenerateExtensionCodeAfter(); Framework = new TypeScriptFrameworkModel(settings); }
public static void GenerateTS(SwaggerDocument document, ApiClientDefinition definition) { var settings = new SwaggerToTypeScriptClientGeneratorSettings() { Template = TypeScriptTemplate.Fetch, OperationNameGenerator = new CustomOperationNameGenerator(), GenerateOptionalParameters = true, UseTransformOptionsMethod = true, ClientBaseClass = "ClientBase", TypeScriptGeneratorSettings = { PropertyNameGenerator = new CustomPropertyNameGenerator(c => c), NullValue = TypeScriptNullValue.Null } }; settings.TypeScriptGeneratorSettings.TemplateFactory = new DotvvmClientTemplateFactory(settings.CodeGeneratorSettings, new[] { typeof(TypeScriptGeneratorSettings).Assembly, typeof(SwaggerToTypeScriptClientGeneratorSettings).Assembly }); var resolver = new TypeScriptTypeResolver(settings.TypeScriptGeneratorSettings); var generator = new DotvvmSwaggerToTypeScriptClientGenerator(document, settings, resolver); var ts = generator.GenerateFile(); var baseClass = definition.CreateBaseClass(); ts = definition.WrapInNamespace(ts, baseClass); File.WriteAllText(definition.TypescriptClient, ts); if (definition.CompileTypescript) { Process.Start(new ProcessStartInfo() { FileName = "tsc", Arguments = definition.TypescriptClient, UseShellExecute = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }).WaitForExit(); } }
public async Task When_body_is_xml_then_correct_TypeScript_is_generated() { //// Arrange var generator = new WebApiToSwaggerGenerator(new WebApiToSwaggerGeneratorSettings()); var document = await generator.GenerateForControllerAsync <MyXmlController>(); var settings = new SwaggerToTypeScriptClientGeneratorSettings { Template = TypeScriptTemplate.JQueryCallbacks }; settings.TypeScriptGeneratorSettings.TypeScriptVersion = 1.8m; //// Act var gen = new SwaggerToTypeScriptClientGenerator(document, settings); var code = gen.GenerateFile(); //// Assert Assert.IsTrue(code.Contains("(xmlDocument: string, ")); Assert.IsTrue(code.Contains("const content_ = xmlDocument;")); Assert.IsTrue(code.Contains("\"Content-Type\": \"application/xml\"")); }
public async Task GenerateTS() { var document = await GetSwaggerDocument(); var settings = new SwaggerToTypeScriptClientGeneratorSettings() { Template = TypeScriptTemplate.Fetch, OperationNameGenerator = new CustomNameGenerator() }; settings.TypeScriptGeneratorSettings.PropertyNameGenerator = new MyPropertyNameGenerator(c => ConversionUtilities.ConvertToLowerCamelCase(c, true)); settings.TypeScriptGeneratorSettings.NullValue = NJsonSchema.CodeGeneration.TypeScript.TypeScriptNullValue.Null; var generator = new SwaggerToTypeScriptClientGenerator(document, settings); var ts = generator.GenerateFile(); ts = "namespace " + Namespace + " {\n" + ConversionUtilities.Tab(ts, 1).TrimEnd('\n') + "\n}\n"; Context.ReturnFile(Encoding.UTF8.GetBytes(ts), "ApiClient.ts", "text/plain"); //File.WriteAllText(TSPath, generator.GenerateFile()); }
public string GenerateCode() { var doc = Task.Run(async() => await GetSwaggerDocAsync()).Result; var settings = new SwaggerToTypeScriptClientGeneratorSettings() { GenerateClientClasses = true, GenerateDtoTypes = true, ClassName = "{controller}ApiClient", PromiseType = PromiseType.Promise, Template = TypeScriptTemplate.Angular, OperationNameGenerator = new MultipleClientsFromOperationIdOperationNameGenerator() }; settings.TypeScriptGeneratorSettings.TypeStyle = TypeScriptTypeStyle.Class; settings.TypeScriptGeneratorSettings.TypeScriptVersion = 2.2m; settings.TypeScriptGeneratorSettings.MarkOptionalProperties = true; var generator = new SwaggerToTypeScriptClientGenerator(doc, settings); var code = generator.GenerateFile(); var removeAnnoyingBaseApiAndVerRegex = new Regex(@"apiv\d+", RegexOptions.IgnoreCase); code = removeAnnoyingBaseApiAndVerRegex.Replace(code, ""); if (UseJwt) { code = code.Replace("from '@angular/http';", "from '@angular/http';\nimport { AuthHttp } from 'angular2-jwt';"); code = code.Replace("@Inject(Http) http: Http", "@Inject(AuthHttp) http: AuthHttp"); code = code.Replace("private http: Http;", "private http: AuthHttp;"); } code = ReplaceEnums(code); code = NormalizeEnums(code); code = ReplaceExtraLineBreaks(code); return(code); }
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); }
private async void GenerateTypescriptApiClient() { try { var document = await SwaggerDocument.FromUrlAsync("http://localhost:30000/swagger/v1/swagger.json"); var settings = new SwaggerToTypeScriptClientGeneratorSettings { ClassName = "{controller}Client", GenerateClientClasses = true, GenerateOptionalParameters = true, GenerateResponseClasses = true, }; var generator = new SwaggerToTypeScriptClientGenerator(document, settings); var code = generator.GenerateFile(); File.WriteAllText("TypescriptApiClient.ts", code); } catch (Exception ex) { } }