conocimientoapi-integration-patternstemplates/5594 B
ApiResponse.cs.template
Fichero que /hv:api-integration-patterns usa o materializa en el proyecto. Se muestra tal cual está en el plugin.
// TEMPLATE: API Response Wrappers
// Uso: Wrappers genéricos para respuestas de API con manejo de errores
namespace MyCompany.MyApp.Infrastructure.ApiClients.Models;
/// <summary>
/// Wrapper genérico para respuestas exitosas/fallidas
/// </summary>
public record ApiResponse<T>
{
public bool Success { get; init; }
public T? Data { get; init; }
public string? ErrorMessage { get; init; }
public string? ErrorCode { get; init; }
public int StatusCode { get; init; }
public DateTime Timestamp { get; init; } = DateTime.UtcNow;
public Dictionary<string, string>? Metadata { get; init; }
/// <summary>
/// Crea una respuesta exitosa
/// </summary>
public static ApiResponse<T> SuccessResponse(T data, int statusCode = 200)
=> new()
{
Success = true,
Data = data,
StatusCode = statusCode
};
/// <summary>
/// Crea una respuesta de error
/// </summary>
public static ApiResponse<T> ErrorResponse(
string errorMessage,
int statusCode = 500,
string? errorCode = null)
=> new()
{
Success = false,
ErrorMessage = errorMessage,
ErrorCode = errorCode,
StatusCode = statusCode
};
/// <summary>
/// Crea una respuesta de error desde excepción
/// </summary>
public static ApiResponse<T> FromException(Exception ex, int statusCode = 500)
=> new()
{
Success = false,
ErrorMessage = ex.Message,
ErrorCode = ex.GetType().Name,
StatusCode = statusCode,
Metadata = new Dictionary<string, string>
{
["ExceptionType"] = ex.GetType().FullName ?? "Unknown",
["StackTrace"] = ex.StackTrace ?? "N/A"
}
};
}
/// <summary>
/// Respuesta paginada genérica
/// </summary>
public record PaginatedApiResponse<T>
{
public List<T> Items { get; init; } = new();
public int TotalCount { get; init; }
public int Page { get; init; }
public int PageSize { get; init; }
public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);
public bool HasNextPage => Page < TotalPages;
public bool HasPreviousPage => Page > 1;
public string? NextPageUrl { get; init; }
public string? PreviousPageUrl { get; init; }
public static PaginatedApiResponse<T> Create(
List<T> items,
int totalCount,
int page,
int pageSize,
string? baseUrl = null)
{
var result = new PaginatedApiResponse<T>
{
Items = items,
TotalCount = totalCount,
Page = page,
PageSize = pageSize
};
if (!string.IsNullOrEmpty(baseUrl))
{
if (result.HasNextPage)
result = result with { NextPageUrl = $"{baseUrl}?page={page + 1}&pageSize={pageSize}" };
if (result.HasPreviousPage)
result = result with { PreviousPageUrl = $"{baseUrl}?page={page - 1}&pageSize={pageSize}" };
}
return result;
}
}
/// <summary>
/// Respuesta de validación con errores por campo
/// </summary>
public record ValidationErrorResponse
{
public string Message { get; init; } = "Validation error";
public Dictionary<string, List<string>> Errors { get; init; } = new();
public int StatusCode { get; init; } = 400;
public static ValidationErrorResponse Create(Dictionary<string, List<string>> errors)
=> new() { Errors = errors };
public static ValidationErrorResponse Create(string field, string error)
=> new()
{
Errors = new Dictionary<string, List<string>>
{
[field] = new List<string> { error }
}
};
}
/// <summary>
/// Respuesta estándar de API externa (cuando la API externa usa este formato)
/// </summary>
public record ExternalApiResponse<T>
{
public T? Result { get; init; }
public string? Status { get; init; }
public string? Message { get; init; }
public int? Code { get; init; }
public List<string>? Errors { get; init; }
public bool IsSuccess => Status?.Equals("success", StringComparison.OrdinalIgnoreCase) == true
|| Code is >= 200 and < 300;
}
/// <summary>
/// Extension methods para trabajar con respuestas
/// </summary>
public static class ApiResponseExtensions
{
/// <summary>
/// Convierte resultado nullable en ApiResponse
/// </summary>
public static ApiResponse<T> ToApiResponse<T>(this T? data, string? notFoundMessage = null)
where T : class
{
return data is not null
? ApiResponse<T>.SuccessResponse(data)
: ApiResponse<T>.ErrorResponse(notFoundMessage ?? "Resource not found", 404, "NOT_FOUND");
}
/// <summary>
/// Ejecuta acción y captura en ApiResponse
/// </summary>
public static async Task<ApiResponse<T>> ExecuteSafelyAsync<T>(Func<Task<T>> action)
{
try
{
var result = await action();
return ApiResponse<T>.SuccessResponse(result);
}
catch (HttpRequestException ex)
{
return ApiResponse<T>.FromException(ex, 503); // Service Unavailable
}
catch (TimeoutException ex)
{
return ApiResponse<T>.FromException(ex, 504); // Gateway Timeout
}
catch (Exception ex)
{
return ApiResponse<T>.FromException(ex, 500);
}
}
}