more work on api

This commit is contained in:
2024-08-15 13:03:24 +02:00
parent 4df972c7a4
commit c24b460a0d
2 changed files with 32 additions and 8 deletions

View File

@@ -0,0 +1,19 @@
using System.Net;
namespace Pilz.Networking.Api;
public record class ApiResult(
HttpStatusCode StatusCode,
ApiMessage? Message = null,
string? StatusDescription = null)
{
public static ApiResult Ok()
{
return new(HttpStatusCode.OK);
}
public static ApiResult Ok(ApiMessage message)
{
return new(HttpStatusCode.OK, message);
}
}

View File

@@ -1,8 +1,6 @@
using Pilz.Extensions.Reflection;
using System;
using System.Net;
using System.Reflection;
using System.Reflection.PortableExecutable;
namespace Pilz.Networking.Api;
@@ -12,6 +10,8 @@ public class ApiServer(string apiUrl) : ApiClient, IApiServer
protected readonly Dictionary<Type, IMessageSerializer> serializers = [];
protected readonly HttpListener httpListener = new();
protected record PrivateApiResult(ApiResult Original, string? ResultJson);
public string ApiUrl { get; } = apiUrl;
public IMessageSerializer Serializer { get; set; } = new DefaultMessageSerializer();
@@ -40,8 +40,8 @@ public class ApiServer(string apiUrl) : ApiClient, IApiServer
if (method.GetCustomAttribute<MessageHandlerAttribute>() is not MessageHandlerAttribute attribute
|| method.GetParameters().FirstOrDefault() is not ParameterInfo parameter
|| !parameter.ParameterType.IsAssignableTo(typeof(ApiMessage))
|| !method.ReturnType.IsAssignableTo(typeof(ApiMessage)))
throw new NotSupportedException("The first parameter needs to be of type ApiMessage and must also return an ApiMessage object and the method must have the MessageHAndlerAttribute.");
|| !method.ReturnType.IsAssignableTo(typeof(ApiResult)))
throw new NotSupportedException("The first parameter needs to be of type ApiMessage and must return an ApiResult object and the method must have the MessageHandlerAttribute.");
// Add handler
handlers.Add(ApiUrl + attribute.Url, handler);
@@ -96,7 +96,7 @@ public class ApiServer(string apiUrl) : ApiClient, IApiServer
}
}
protected virtual string? HandleMessage(string url, string json)
protected virtual PrivateApiResult? HandleMessage(string url, string json)
{
// Get handler
if (!handlers.TryGetValue(url, out var handler)
@@ -112,14 +112,19 @@ public class ApiServer(string apiUrl) : ApiClient, IApiServer
return null;
// Invoke handler
if (handler.DynamicInvoke(message) is not ApiMessage result)
if (handler.DynamicInvoke(message) is not ApiResult result)
return null;
// Return result without message
if (result.Message is null)
return new(result, null);
// Serializer
if (serializer.Serialize(result) is not string resultStr)
if (serializer.Serialize(result.Message) is not string resultStr)
return null;
return resultStr;
// Return result with message
return new(result, resultStr);
}
protected virtual IMessageSerializer GetSerializer(Type? t)