using FluentValidation.Results;
namespace zero.Stores;
public partial class StoreOperations : IStoreOperations
{
///
public virtual Task> Create(T model, Func> validate = null) where T : ZeroIdEntity, new() => Save(model, validate);
///
public virtual Task> Update(T model, Func> validate = null) where T : ZeroIdEntity, new() => Save(model, validate);
///
protected virtual async Task> Save(T model, Func> validate = null) where T : ZeroIdEntity, new()
{
if (model == null)
{
return Result.Fail("@errors.onsave.empty");
}
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.Fail("@errors.onsave.noidmatch");
}
isUpdate = true;
}
// validate flavor
if (model is ISupportsFlavors flavorModel && !flavorModel.Flavor.IsNullOrEmpty())
{
if (!Flavors.Exists(flavorModel.Flavor))
{
return Result.Fail("@errors.onsave.flavornotfound");
}
}
// prepare model
PrepareForSave(model);
// run validator
if (validate != null)
{
ValidationResult validation = await validate(model);
if (!validation.IsValid)
{
return Result.Fail(validation);
}
}
// create ID before-hand so interceptors can use it
if (!isUpdate)
{
model.Id = await GenerateId(model);
}
// run interceptor
InterceptorInstruction 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();
return Result.Success(model);
}
}