using FluentValidation;
using Raven.Client.Documents;
namespace zero.Raven;
public static class ValidatorExtensions
{
///
/// Check if this value is unique within a collection
///
public static IRuleBuilderOptions Unique(this IRuleBuilder ruleBuilder, IRavenOperations ops)
where T : ZeroIdEntity
{
return ruleBuilder.MustAsync(async (entity, value, context, cancellation) =>
{
bool any = await ops.Session.Advanced.AsyncDocumentQuery()
.WhereNotEquals(nameof(ZeroIdEntity.Id), entity.Id)
.WhereEquals(context.PropertyName.ToPascalCaseId(), value)
.AnyAsync(cancellation);
return !any;
}).WithMessage("@errors.forms.not_unique");
}
///
/// Check if this value is unique within a collection
///
public static IRuleBuilderOptions Unique(this IRuleBuilder ruleBuilder, IRavenOperations ops)
{
return ruleBuilder.MustAsync(async (entity, value, context, cancellation) =>
{
bool any = await ops.Session.Advanced.AsyncDocumentQuery()
.WhereEquals(context.PropertyName.ToPascalCaseId(), value)
.AnyAsync(cancellation);
return !any;
}).WithMessage("@errors.forms.not_unique");
}
///
/// Check if this value is at least set once to the expected value within a collection
///
public static IRuleBuilderOptions ExpectAnyUnique(this IRuleBuilder ruleBuilder, IRavenOperations ops, TProperty expectedValue)
where T : ZeroIdEntity
{
return ruleBuilder.MustAsync(async (entity, value, context, cancellation) =>
{
return await ops.Session.Advanced.AsyncDocumentQuery()
.WhereNotEquals(nameof(ZeroIdEntity.Id), entity.Id)
.WhereEquals(context.PropertyName.ToPascalCaseId(), expectedValue)
.AnyAsync(cancellation);
}).WithMessage("@errors.forms.not_unique_alone");
}
///
/// Check if this reference exists and is an entity which can be referenced
///
public static IRuleBuilderOptions Exists(this IRuleBuilder ruleBuilder, IRavenOperations ops)
where T : ZeroIdEntity
{
return ruleBuilder.Exists(ops);
}
///
/// Check if this reference exists and is an entity which can be referenced
///
public static IRuleBuilderOptions Exists(this IRuleBuilder ruleBuilder, IRavenOperations ops)
where TCollection : ZeroIdEntity
{
return ruleBuilder.MustAsync(async (entity, id, context, cancellation) =>
{
if (id.IsNullOrWhiteSpace())
{
return true;
}
return await ops.Session.Query().AnyAsync(x => x.Id == id);
}).WithMessage("@errors.forms.reference_notfound");
}
}