Added RouteName and Request/Response handling to the code generator. More work is needed.

This commit is contained in:
2023-02-05 10:59:29 -08:00
parent 74f8921f7a
commit 1475159f1c
5 changed files with 199 additions and 52 deletions

View File

@@ -293,7 +293,7 @@ namespace MontoyaTech.Rest.Net
writer.WriteBreak().WriteLine("public string BaseUrl;");
writer.WriteBreak().WriteLine("private HttpClient HttpClient;");
writer.WriteBreak().WriteLine("public HttpClient HttpClient;");
//Create fields foreach route group so they can be accessed.
foreach (var group in routeGroups)
@@ -353,8 +353,6 @@ namespace MontoyaTech.Rest.Net
GenerateCSharpIncludedProperty(property, writer);
writer.Outdent().WriteLine("}");
System.Diagnostics.Debugger.Break();
}
private static void GenerateCSharpIncludedField(FieldInfo field, CodeWriter writer)
@@ -407,11 +405,14 @@ namespace MontoyaTech.Rest.Net
var methodInfo = route.GetTarget().GetMethodInfo();
var routeName = methodInfo.GetCustomAttribute<RouteName>();
var routeRequest = methodInfo.GetCustomAttribute<RouteRequest>();
var routeResponse = methodInfo.GetCustomAttribute<RouteResponse>();
writer.Write($"public {(routeResponse == null ? "void" : GetTypeFullyResolvedName(routeResponse.ResponseType))} {methodInfo.Name}(");
//Construct the routes request function
writer.Write($"public {(routeResponse == null ? "void" : GetTypeFullyResolvedName(routeResponse.ResponseType))} {(routeName == null ? methodInfo.Name : routeName.Name)}(");
var parameters = methodInfo.GetParameters();
@@ -432,21 +433,8 @@ namespace MontoyaTech.Rest.Net
writer.WriteLine(")").WriteLine("{").Indent();
//Generate code to send a request
/*
* var response = HttpClient.Send(new HttpRequestMessage(HttpMethod.Post, $"{Auth0Url}/oauth/token")
{
Content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("redirect_uri", redirectUrl),
new KeyValuePair<string, string>("client_id", ClientId)
})
})
*/
writer.Write($"var request = new HttpRequestMessage(");
//Generate the message code
writer.WriteBreak().Write($"var message = new HttpRequestMessage(");
switch (route.Method.ToLower())
{
@@ -460,12 +448,60 @@ namespace MontoyaTech.Rest.Net
throw new NotSupportedException("Unsupport route method:" + route.Method);
}
writer.WriteSeparator().Write('$').WriteString($"{{this.Client.BaseUrl}}/{route.Syntax}");
writer.WriteSeparator().Write('$').Write('"').Write("{this.Client.BaseUrl}");
writer.WriteLine(");");
//Reconstruct the route syntax into a request url.
var components = route.Syntax.Split('/');
int argumentIndex = 0;
foreach (var component in components)
{
if (!string.IsNullOrWhiteSpace(component))
{
writer.Write('/');
if (component.StartsWith("{"))
{
writer.Write("{").Write(parameters[argumentIndex++ + 1].Name).Write("}");
}
else if (component == "*")
{
writer.Write("*");
}
else if (component == "**")
{
break;
}
else
{
writer.Write(component);
}
}
}
writer.Write('"').WriteLine(");");
//Add the request content if any.
if (routeRequest != null)
{
writer.WriteBreak().WriteLine("message.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(request));");
}
//Generate the response code
writer.WriteBreak().WriteLine("var response = this.Client.HttpClient.Send(message);");
//Handle the response
if (routeResponse != null)
writer.WriteLine("return default;");
{
writer.WriteBreak().WriteLine("if (response.StatusCode == System.Net.HttpStatusCode.OK)").Indent();
writer.WriteLine($"return Newtonsoft.Json.JsonConvert.DeserializeObject<{GetTypeFullyResolvedName(routeResponse.ResponseType)}>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());");
writer.Outdent().WriteLine("else").Indent();
writer.WriteLine(@"throw new Exception(""Unexpected Http Response StatusCode:"" + response.StatusCode);").Outdent();
}
else
{
writer.WriteBreak().WriteLine("if (response.StatusCode == System.Net.HttpStatusCode.OK)").Indent();
writer.WriteLine(@"throw new Exception(""Unexpected Http Response StatusCode:"" + response.StatusCode);").Outdent();
}
writer.Outdent().WriteLine("}");
}

View File

@@ -29,6 +29,17 @@ namespace MontoyaTech.Rest.Net
/// </summary>
public ushort Port = 8081;
/// <summary>
/// Returns the BaseUrl for this RouteListener.
/// </summary>
public string BaseUrl
{
get
{
return $"http://localhost:{this.Port}";
}
}
/// <summary>
/// An event to preprocess routes before the route is executed.
/// </summary>

38
Rest.Net/RouteName.cs Normal file
View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MontoyaTech.Rest.Net
{
/// <summary>
/// The outline of an attribute that allows you to rename an attribute in
/// the output code generation.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class RouteName : Attribute
{
/// <summary>
/// The name of this Route.
/// </summary>
public string Name = null;
/// <summary>
/// Creates a new default RouteName.
/// </summary>
public RouteName() { }
/// <summary>
/// Creates a new RouteName with a given name.
/// </summary>
/// <param name="name"></param>
public RouteName(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Cannot be null or whitespace", nameof(name));
this.Name = name;
}
}
}