add some default types to de-duplicate similar implmentations
This commit is contained in:
63
Pilz.Net/Api/Server/BaseHandler.cs
Normal file
63
Pilz.Net/Api/Server/BaseHandler.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using Pilz.Extensions.Reflection;
|
||||
using Pilz.Net.Data;
|
||||
using Pilz.Net.Extensions;
|
||||
using System.Diagnostics;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Pilz.Net.Api.Server;
|
||||
|
||||
public abstract class BaseHandler<TEntity, TUpdateMsg>(IApiServer server)
|
||||
: IApiHandlerInitializer
|
||||
where TEntity : IDataObject
|
||||
where TUpdateMsg : ApiMessage
|
||||
{
|
||||
public abstract string Route { get; }
|
||||
protected virtual bool RegisterGet => true;
|
||||
protected virtual bool RegisterPut => true;
|
||||
protected virtual bool RegisterDelete => true;
|
||||
|
||||
public virtual void Initialize(IApiServer server)
|
||||
{
|
||||
var t = GetType();
|
||||
if (RegisterGet)
|
||||
server.RegisterHandler(t.GetMethod(nameof(Get))!.CreateDelegate(this), new(Route + "/{id}", "GET"), Debugger.IsAttached);
|
||||
if (RegisterPut)
|
||||
server.RegisterHandler(t.GetMethod(nameof(Put))!.CreateDelegate(this), new(Route + "/{id}", "PUT"), Debugger.IsAttached);
|
||||
if (RegisterDelete)
|
||||
server.RegisterHandler(t.GetMethod(nameof(Delete))!.CreateDelegate(this), new(Route + "/{id}", "DELETE"), Debugger.IsAttached);
|
||||
}
|
||||
|
||||
public virtual ApiResult Get(int id)
|
||||
{
|
||||
if (!server.Manager.Find(id, out TEntity? entity))
|
||||
return ApiResult.NotFound();
|
||||
return ToClient(entity).ToItemResult();
|
||||
}
|
||||
|
||||
public virtual ApiResult Put(int id, TUpdateMsg msg)
|
||||
{
|
||||
if (!server.Manager.Find(id, out TEntity? entity))
|
||||
return ApiResult.NotFound();
|
||||
if (UpdateEntity(entity, msg) is ApiResult result)
|
||||
return result;
|
||||
server.Manager.Save(entity, true);
|
||||
return ToClient(entity).ToItemResult();
|
||||
}
|
||||
|
||||
public virtual ApiResult Delete(int id)
|
||||
{
|
||||
server.Manager.Delete<TEntity>(id, true);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
protected virtual TEntity CreateNewEntity()
|
||||
{
|
||||
return Activator.CreateInstance<TEntity>();
|
||||
}
|
||||
|
||||
protected abstract ApiResult? UpdateEntity(TEntity entity, TUpdateMsg msg);
|
||||
|
||||
protected abstract IDataObject ToClient(TEntity entity);
|
||||
}
|
||||
Reference in New Issue
Block a user