86 lines
2.4 KiB
C#
86 lines
2.4 KiB
C#
namespace Indotalent.ConfigBackEnd.Extensions;
|
|
|
|
using Indotalent.Shared.Models;
|
|
using Microsoft.AspNetCore.Http;
|
|
using System.Text.Json;
|
|
|
|
public static class GenericExtensions
|
|
{
|
|
public static bool IsNullOrEmpty<T>(this IEnumerable<T>? enumerable)
|
|
{
|
|
return enumerable == null || !enumerable.Any();
|
|
}
|
|
|
|
public static T? ToObject<T>(this string json)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(json)) return default;
|
|
|
|
return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
});
|
|
}
|
|
|
|
public static string ToJson<T>(this T obj)
|
|
{
|
|
return JsonSerializer.Serialize(obj);
|
|
}
|
|
|
|
public static TDestination MapTo<TDestination>(this object source)
|
|
where TDestination : new()
|
|
{
|
|
var json = JsonSerializer.Serialize(source);
|
|
return JsonSerializer.Deserialize<TDestination>(json) ?? new TDestination();
|
|
}
|
|
|
|
public static string ToCurrency(this decimal value, string culture = "id-ID")
|
|
{
|
|
return value.ToString("C0", new System.Globalization.CultureInfo(culture));
|
|
}
|
|
|
|
public static bool IsBetween<T>(this T value, T low, T high) where T : IComparable<T>
|
|
{
|
|
return value.CompareTo(low) >= 0 && value.CompareTo(high) <= 0;
|
|
}
|
|
|
|
public static IResult ToApiResponse<T>(this PagedList<T> result)
|
|
{
|
|
return Results.Ok(new ApiResponse<List<T>>
|
|
{
|
|
IsSuccess = true,
|
|
StatusCode = 200,
|
|
Value = result.Value,
|
|
Pagination = new PaginationMetadata
|
|
{
|
|
Count = result.Count,
|
|
Top = result.Top,
|
|
Skip = result.Skip
|
|
},
|
|
ServerTime = DateTime.UtcNow
|
|
});
|
|
}
|
|
|
|
public static IResult ToApiResponse<T>(this T? result, string? message = null, int statusCode = 200)
|
|
{
|
|
if (result == null)
|
|
{
|
|
return Results.NotFound(new ApiResponse<T>
|
|
{
|
|
IsSuccess = false,
|
|
StatusCode = 404,
|
|
Message = message ?? "Data not found",
|
|
ServerTime = DateTime.UtcNow
|
|
});
|
|
}
|
|
|
|
return Results.Ok(new ApiResponse<T>
|
|
{
|
|
IsSuccess = true,
|
|
StatusCode = statusCode,
|
|
Message = message,
|
|
Value = result,
|
|
Pagination = null,
|
|
ServerTime = DateTime.UtcNow
|
|
});
|
|
}
|
|
} |