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

57 lines
1.6 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-11-24 15:49:25 +01:00
bool isUpdate = !model.Id.IsNullOrEmpty() && await Session.Advanced.ExistsAsync(model.Id);
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
}
}