using FluentValidation.Results;
namespace zero.Collections;
public abstract partial class CollectionOperations
{
///
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 EntityResult.Fail("@errors.onsave.empty");
}
bool isUpdate = model.Id.IsNullOrEmpty() ? false : await Session.Advanced.ExistsAsync(model.Id);
// prepare model
PrepareForSave(model);
// run validator
if (validate != null)
{
ValidationResult validation = await validate(model);
if (!validation.IsValid)
{
return EntityResult.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 EntityResult.Success(model);
}
}