ApiResponse.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Text.Json.Serialization;
  2. namespace Web.Api.Common;
  3. public sealed class ApiResponse
  4. {
  5. [JsonPropertyName("success")]
  6. public bool Success { get; init; }
  7. [JsonPropertyName("data")]
  8. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
  9. public object? Data { get; init; }
  10. [JsonPropertyName("status")]
  11. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
  12. public int Status { get; init; }
  13. [JsonPropertyName("message")]
  14. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
  15. public string? Message { get; init; }
  16. [JsonPropertyName("errors")]
  17. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
  18. public object? Errors { get; init; }
  19. public static IResult Ok(object? data = null)
  20. {
  21. string? message = null;
  22. if (data is not null)
  23. {
  24. var type = data.GetType();
  25. var msgProp = type.GetProperty("message", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase);
  26. if (msgProp is not null && msgProp.PropertyType == typeof(string))
  27. {
  28. message = msgProp.GetValue(data) as string;
  29. // message 외 다른 속성이 없으면 data를 null로 설정
  30. var otherProps = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(p => !string.Equals(p.Name, "message", StringComparison.OrdinalIgnoreCase));
  31. if (!otherProps.Any())
  32. {
  33. data = null;
  34. }
  35. }
  36. }
  37. return Results.Ok(new ApiResponse
  38. {
  39. Success = true,
  40. Message = message,
  41. Data = data
  42. });
  43. }
  44. public static IResult Created(object? data = null)
  45. {
  46. return Results.Json(new ApiResponse
  47. {
  48. Success = true,
  49. Data = data
  50. }, statusCode: StatusCodes.Status201Created);
  51. }
  52. public static IResult Fail(int status, string message, object? errors = null)
  53. {
  54. return Results.Json(new ApiResponse
  55. {
  56. Success = false,
  57. Status = status,
  58. Message = message,
  59. Errors = errors
  60. }, statusCode: status);
  61. }
  62. }