2022-02-03 13:19:48 +00:00
|
|
|
namespace ASC.Api.Utils;
|
|
|
|
|
|
|
|
public static class Validate
|
2019-06-21 09:07:49 +00:00
|
|
|
{
|
2022-02-07 16:03:16 +00:00
|
|
|
public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : class
|
|
|
|
{
|
|
|
|
return @if(item) ? then() : item;
|
|
|
|
}
|
2019-06-21 09:07:49 +00:00
|
|
|
|
2022-02-07 16:03:16 +00:00
|
|
|
public static T IfNull<T>(this T item, Func<T> func) where T : class
|
|
|
|
{
|
|
|
|
return item.If((x) => x == default(T), func);
|
|
|
|
}
|
2019-06-21 09:07:49 +00:00
|
|
|
|
2022-02-07 16:03:16 +00:00
|
|
|
public static T ThrowIfNull<T>(this T item, Exception e) where T : class
|
|
|
|
{
|
|
|
|
return item.IfNull(() => { throw e; });
|
|
|
|
}
|
2019-06-21 09:07:49 +00:00
|
|
|
|
2022-02-07 16:03:16 +00:00
|
|
|
public static T NotFoundIfNull<T>(this T item) where T : class
|
|
|
|
{
|
|
|
|
return NotFoundIfNull(item, "Item not found");
|
|
|
|
}
|
2019-06-21 09:07:49 +00:00
|
|
|
|
2022-02-07 16:03:16 +00:00
|
|
|
public static T NotFoundIfNull<T>(this T item, string message) where T : class
|
|
|
|
{
|
|
|
|
return item.IfNull(() => { throw new ItemNotFoundException(message); });
|
|
|
|
}
|
2020-07-02 15:15:52 +00:00
|
|
|
|
2022-02-07 16:03:16 +00:00
|
|
|
public static T? NullIfDefault<T>(this T item) where T : struct
|
|
|
|
{
|
|
|
|
return EqualityComparer<T>.Default.Equals(item, default(T)) ? default(T?) : item;
|
|
|
|
}
|
2019-06-21 09:07:49 +00:00
|
|
|
}
|