Files
mixtape/zero.Core/Stores/StoreOperations.Write.cs
T

79 lines
2.0 KiB
C#
Raw Normal View History

2021-11-23 11:35:01 +01:00
using FluentValidation.Results;
2021-11-23 22:56:22 +01:00
namespace zero.Stores;
2021-11-23 11:35:01 +01:00
2021-11-27 18:09:27 +01:00
public partial class StoreOperations : IStoreOperations
2021-11-23 11:35:01 +01:00
{
/// <inheritdoc />
2021-11-26 15:47:11 +01:00
public virtual Task<Result<T>> Create<T>(T model, Func<T, Task<ValidationResult>> validate = null) where T : ZeroIdEntity, new() => Save(model, validate);
2021-11-23 15:43:21 +01:00
/// <inheritdoc />
2021-11-26 15:47:11 +01:00
public virtual Task<Result<T>> Update<T>(T model, Func<T, Task<ValidationResult>> validate = null) where T : ZeroIdEntity, new() => Save(model, validate);
2021-11-23 15:43:21 +01:00
/// <inheritdoc />
2021-11-26 15:47:11 +01:00
protected virtual async Task<Result<T>> Save<T>(T model, Func<T, Task<ValidationResult>> validate = null) where T : ZeroIdEntity, new()
2021-11-23 11:35:01 +01:00
{
if (model == null)
{
2021-11-26 15:47:11 +01:00
return Result<T>.Fail("@errors.onsave.empty");
2021-11-23 11:35:01 +01:00
}
2021-12-02 14:44:48 +01:00
bool isUpdate = false;
// check if the Id for a model already exists
if (!model.Id.IsNullOrEmpty())
{
bool exists = await Session.Advanced.ExistsAsync(model.Id);
if (!exists)
{
return Result<T>.Fail("@errors.onsave.noidmatch");
}
isUpdate = true;
}
// validate flavor
if (model is ISupportsFlavors flavorModel && !flavorModel.Flavor.IsNullOrEmpty())
{
if (!Flavors.Exists<T>(flavorModel.Flavor))
{
return Result<T>.Fail("@errors.onsave.flavornotfound");
}
}
2021-11-23 11:35:01 +01:00
// prepare model
PrepareForSave(model);
// run validator
if (validate != null)
{
ValidationResult validation = await validate(model);
if (!validation.IsValid)
{
2021-11-26 15:47:11 +01:00
return Result<T>.Fail(validation);
2021-11-23 11:35:01 +01:00
}
}
// create ID before-hand so interceptors can use it
if (!isUpdate)
{
model.Id = await GenerateId(model);
}
// run interceptor
InterceptorInstruction<T> instruction = isUpdate ? Interceptors.ForUpdate(model) : Interceptors.ForCreate(model);
if (!await instruction.Start())
{
return instruction.Result;
}
// store our model
await Session.StoreAsync(model);
await instruction.Complete();
await Session.SaveChangesAsync();
2021-11-26 15:47:11 +01:00
return Result<T>.Success(model);
2021-11-23 11:35:01 +01:00
}
}