Skip to content

Instantly share code, notes, and snippets.

@rstackhouse
Last active January 26, 2022 14:54
Show Gist options
  • Save rstackhouse/ee8bf4c13814b0303ff98931e1851ae0 to your computer and use it in GitHub Desktop.
Save rstackhouse/ee8bf4c13814b0303ff98931e1851ae0 to your computer and use it in GitHub Desktop.
Console app to generate a gateway to a service using NSwag and a swagger document.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NSwag;
using NSwag.CodeGeneration.CSharp;
namespace GatewayGenerator
{
class Program
{
protected static string GetArg(List<string> argsList, string argName)
{
int index = -1;
var pos = argsList.Select((s, i) => new {i, s})
.Where(a => a.s == $"--{argName}")
.FirstOrDefault();
if (pos != null)
{
index = pos.i + 1;
}
var val = index != -1 ? argsList[index] : null;
if (val == null || val.StartsWith("--"))
{
Console.WriteLine($"Missing arg --{argName}");
}
return val;
}
async static Task Main(string[] args)
{
if (args.Length > 0)
{
var argsList = new List<string>(args);
// --url
var swaggerUrl = GetArg(argsList, "url");
if (swaggerUrl == null)
{
return;
}
// --class-name
var className = GetArg(argsList, "class-name");
if (className == null)
{
return;
}
// --namespace
var namespaceValue = GetArg(argsList, "namespace");
if (namespaceValue == null)
{
return;
}
// --configuration-class
var configurationClass = GetArg(argsList, "configuration-class");
if (configurationClass == null)
{
return;
}
System.Net.WebClient wclient = new System.Net.WebClient();
var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString(swaggerUrl));
wclient.Dispose();
var settings = new CSharpClientGeneratorSettings
{
ConfigurationClass = configurationClass,
ClassName = className,
InjectHttpClient = false,
CSharpGeneratorSettings =
{
Namespace = namespaceValue
},
UseHttpClientCreationMethod = true
};
var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();
Console.WriteLine(code);
}
else
{
Console.WriteLine("Usage: GatewayGenerator --url <url to swagger.json>"
+" --class-name <e.g. SomeOtherServiceGateway>"
+" --namespace <e.g. SomeService.Gateways>"
+" --configuration-class <class name of configuration>");
}
} // end Main
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment