some more work on api

This commit is contained in:
Pilzinsel64
2024-08-16 09:19:03 +02:00
parent 6f5e012cb6
commit df4adb8435
8 changed files with 90 additions and 27 deletions

View File

@@ -54,7 +54,9 @@ public class ApiServer(string apiUrl) : IApiServer
// Sanity checks
if (method.GetCustomAttribute<MessageHandlerAttribute>() is not MessageHandlerAttribute attribute
|| method.GetParameters().FirstOrDefault() is not ParameterInfo parameter
|| !parameter.ParameterType.IsAssignableTo(typeof(ApiMessage))
|| !parameter.ParameterType.IsGenericType
|| parameter.ParameterType.GenericTypeArguments.Length != 1
|| !parameter.ParameterType.GenericTypeArguments[0].IsAssignableTo(typeof(ApiMessage))
|| !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.");
@@ -146,8 +148,11 @@ public class ApiServer(string apiUrl) : IApiServer
// Check authentication
Log.Debug("Check authentication");
if (attribute.RequiesAuth && (string.IsNullOrWhiteSpace(authKey) || !CheckAuthentication(authKey)))
return null;
var isAuthenticated = false;
if (!string.IsNullOrWhiteSpace(authKey) && DecodeAuthKey(authKey) is string authKeyDecoded)
isAuthenticated = CheckAuthentication(authKeyDecoded);
else
authKeyDecoded = null!;
// Get required infos
Log.Debug("Find other infos");
@@ -161,7 +166,8 @@ public class ApiServer(string apiUrl) : IApiServer
// Invoke handler
Log.Debug("Invoke handler");
if (handler.DynamicInvoke(message) is not ApiResult result)
var parameters = BuildParameters(handler, () => message, () => new(message, isAuthenticated, authKeyDecoded));
if (handler.DynamicInvoke(parameters) is not ApiResult result)
return null;
// Return result without message
@@ -179,6 +185,22 @@ public class ApiServer(string apiUrl) : IApiServer
return new(result, resultStr);
}
protected virtual object?[]? BuildParameters(Delegate handler, Func<ApiMessage> getMessage, Func<ApiRequestInfo> getRequestInfo)
{
var infos = handler.Method.GetParameters();
var objs = new List<object?>();
foreach (var info in infos)
{
if (info.ParameterType.IsAssignableTo(typeof(ApiMessage)))
objs.Add(getMessage());
else if (info.ParameterType.IsAssignableTo(typeof(ApiRequestInfo)))
objs.Add(getRequestInfo());
}
return [.. objs];
}
protected virtual IMessageSerializer GetSerializer(Type? t)
{
if (t is not null)
@@ -204,4 +226,9 @@ public class ApiServer(string apiUrl) : IApiServer
}
return false;
}
protected virtual string? DecodeAuthKey(string authKey)
{
return authKey;
}
}