107 lines
2.4 KiB
C#
107 lines
2.4 KiB
C#
using BS.Shared.Core;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace BS.Shared.DataContracts.MikePHPContracts
|
|
{
|
|
public class ApiResponse<T>
|
|
{
|
|
public T Data { get; set; }
|
|
|
|
public List<AppError> Errors { get; set; }
|
|
|
|
public List<string> ErrorStrings { get; set; }
|
|
|
|
public List<string> Messages { get; set; }
|
|
|
|
public Dictionary<string, object> Meta { get; set; }
|
|
|
|
public string TraceId { get; set; }
|
|
|
|
public DateTime Timestamp { get; set; } = DateTime.Now;
|
|
|
|
public int StatusCode { get; set; } = 200;
|
|
|
|
public bool Success => (Errors?.Count ?? 0) == 0 && (ErrorStrings?.Count ?? 0) == 0;
|
|
|
|
//Factory Methods
|
|
public static ApiResponse<T> SuccessResponse(T data, List<string> messages = null, Dictionary<string, object> meta = null)
|
|
{
|
|
return new ApiResponse<T>
|
|
{
|
|
Data = data,
|
|
Messages = messages ?? new List<string>(),
|
|
Meta = meta ?? new Dictionary<string, object>(),
|
|
};
|
|
}
|
|
|
|
public static ApiResponse<T> FailureResponse(List<AppError> errors, int statusCode = 400, string traceId = null)
|
|
{
|
|
return new ApiResponse<T>
|
|
{
|
|
Errors = errors,
|
|
StatusCode = statusCode,
|
|
TraceId = traceId
|
|
};
|
|
}
|
|
|
|
public static ApiResponse<T> FailureResponse(AppError error, int statusCode = 400, string traceId = null)
|
|
{
|
|
return FailureResponse(new List<AppError> { error }, statusCode, traceId);
|
|
}
|
|
|
|
//Parse Methods
|
|
public static ApiResponse<T> Parse(object obj)
|
|
{
|
|
var response = new ApiResponse<T>();
|
|
|
|
if (typeof(T) == typeof(byte[]))
|
|
{
|
|
response.Data = (T)obj;
|
|
|
|
var response_string = Encoding.UTF8.GetString(obj as byte[]);
|
|
var kv = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(response_string);
|
|
|
|
if (kv is object && kv.TryGetValue("errors", out var errors))
|
|
{
|
|
response.ErrorStrings = errors;
|
|
}
|
|
|
|
}
|
|
else
|
|
{
|
|
throw new NotImplementedException("typeof(T) not implemented!");
|
|
}
|
|
|
|
return response;
|
|
}
|
|
|
|
public string ToErrorString()
|
|
{
|
|
var sb = new StringBuilder();
|
|
|
|
if (Errors is object && Errors.Any())
|
|
{
|
|
foreach (var appError in Errors)
|
|
{
|
|
sb.AppendLine(appError.Displayname);
|
|
}
|
|
}
|
|
|
|
if (ErrorStrings is object && ErrorStrings.Any())
|
|
{
|
|
foreach (var error in ErrorStrings)
|
|
{
|
|
sb.AppendLine(error);
|
|
}
|
|
}
|
|
|
|
return sb.ToString();
|
|
}
|
|
}
|
|
}
|