Repository navigation
Expand file tree
/
Copy pathApiResult.cs
More file actions
273 lines (231 loc) · 9.92 KB
/
Copy pathApiResult.cs
File metadata and controls
273 lines (231 loc) · 9.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ServiceStack.Model;
using ServiceStack.Text;
namespace ServiceStack;
public static class ApiResult
{
public const string FieldErrorCode = "ValidationException";
public static ApiResult<TResponse> Create<TResponse>(TResponse response) => new(response);
public static ApiResult<TResponse> CreateError<TResponse>(ResponseStatus errorStatus) => new(errorStatus);
public static ApiResult<EmptyResponse> CreateError(ResponseStatus errorStatus) => new(errorStatus);
public static ApiResult<TResponse> CreateError<TResponse>(string message, string? errorCode = nameof(Exception)) =>
new(ErrorUtils.CreateError(message, errorCode));
public static ApiResult<EmptyResponse> CreateError(string message, string? errorCode = nameof(Exception)) =>
new(ErrorUtils.CreateError(message, errorCode));
public static ApiResult<TResponse> CreateError<TResponse>(Exception ex) => new(ErrorUtils.CreateError(ex));
public static ApiResult<EmptyResponse> CreateError(Exception ex) => new(ErrorUtils.CreateError(ex));
public static ApiResult<TResponse> CreateFieldError<TResponse>(string fieldName, string message, string? errorCode = FieldErrorCode)
{
var apiResult = new ApiResult<TResponse>();
apiResult.AddFieldError(fieldName, message, errorCode);
return apiResult;
}
public static ApiResult<EmptyResponse> CreateFieldError(string fieldName, string message,
string? errorCode = FieldErrorCode)
{
var apiResult = new ApiResult<EmptyResponse>();
apiResult.AddFieldError(fieldName, message, errorCode);
return apiResult;
}
}
public class ApiResult<TResponse> : IHasErrorStatus
{
public TResponse? Response { get; }
public ResponseStatus? Error { get; private set; }
public bool Failed => Error.IsError();
public bool Succeeded => !Failed && Response != null;
public bool Completed => Response != null || Error != null;
public string? ErrorMessage => Error?.Message;
public ResponseError[] Errors => Error?.Errors.ToArray() ?? TypeConstants<ResponseError>.EmptyArray;
public string? ErrorSummary => Error != null && Errors.Length == 0
? Error.Message
: null;
public ApiResult() { }
public ApiResult(TResponse response) => Response = response;
public ApiResult(ResponseStatus errorStatus) => Error = errorStatus;
public string? FieldErrorMessage(string fieldName) => Error.FieldErrorMessage(fieldName);
public ResponseError? FieldError(string fieldName) => Error.FieldError(fieldName);
public bool HasFieldError(string fieldName) => Error.HasErrorField(fieldName);
public void ClearErrors() => Error = null;
public void AddFieldError(string fieldName, string message, string? errorCode = ApiResult.FieldErrorCode)
{
Error ??= new ResponseStatus {
ErrorCode = ErrorUtils.FieldErrorCode,
Message = message,
};
Error.AddFieldError(fieldName, message);
}
public void SetError(string errorMessage, string errorCode = nameof(Exception))
{
Error ??= new ResponseStatus();
Error.Message = errorMessage;
Error.ErrorCode = errorCode;
}
}
public static class ErrorUtils
{
public const string FieldErrorCode = "ValidationException";
public static bool IsSuccess(this ResponseStatus? status) => !status.IsError();
public static bool IsError(this ResponseStatus? status) => status?.ErrorCode != null || status?.Message != null;
public static ResponseError? FieldError(this ResponseStatus? status, string fieldName) => status?.Errors?
.FirstOrDefault(x => string.Equals(x.FieldName, fieldName, StringComparison.OrdinalIgnoreCase));
public static string? FieldErrorMessage(this ResponseStatus? status, string fieldName) => status?.Errors?
.FirstOrDefault(x => string.Equals(x.FieldName, fieldName, StringComparison.OrdinalIgnoreCase))?.Message;
public static bool HasErrorField(this ResponseStatus? status, string fieldName) =>
status?.FieldError(fieldName) != null;
public static bool ShowSummary(this ResponseStatus? status, params string[] exceptFields)
{
if (!status.IsError())
return false;
// Don't show summary message if an error for a visible field exists
foreach (var fieldName in exceptFields)
{
if (status.HasErrorField(fieldName))
return false;
}
return true;
}
public static string? SummaryMessage(this ResponseStatus? status, params string[] exceptFields)
{
if (status.ShowSummary(exceptFields))
{
// Return first field error that's not visible
if (status?.Errors != null)
{
var fieldSet = new HashSet<string>(exceptFields, StringComparer.OrdinalIgnoreCase);
foreach (var errorField in status.Errors)
{
if (fieldSet.Contains(errorField.FieldName))
continue;
return errorField.Message;
}
}
// otherwise return summary message
return status?.Message;
}
return null;
}
public static ResponseStatus AsResponseStatus(this Exception ex) => CreateError(ex);
public static ResponseStatus CreateError(Exception ex) => ex switch {
IResponseStatusConvertible rsc => rsc.ToResponseStatus(),
IHasResponseStatus hasStatus => hasStatus.ResponseStatus,
ArgumentException { ParamName: { } } ae => CreateFieldError(ae.ParamName, ex.Message, ex.GetType().Name),
_ => CreateError(ex.Message, ex.GetType().Name)
};
public static ResponseStatus CreateError(string message, string? errorCode = nameof(Exception)) => new() {
ErrorCode = errorCode,
Message = message,
};
public static ResponseStatus CreateFieldError(string fieldName, string errorMessage,
string errorCode = FieldErrorCode) =>
new ResponseStatus().AddFieldError(fieldName, errorMessage, errorCode);
public static ResponseStatus AddFieldError(this ResponseStatus status, string fieldName, string errorMessage,
string errorCode = FieldErrorCode)
{
var fieldError = status.FieldError(fieldName);
if (fieldError != null)
{
fieldError.ErrorCode = errorCode;
fieldError.Message = errorMessage;
}
else
{
status.Errors ??= new List<ResponseError>();
status.Errors.Add(new ResponseError {
FieldName = fieldName,
Message = errorMessage,
ErrorCode = errorCode,
});
}
return status;
}
}
public static class ApiResultUtils
{
public static ApiResult<TResponse> ToApiResult<TResponse>(this Exception ex) => ApiResult.CreateError<TResponse>(ex);
public static ApiResult<EmptyResponse> ToApiResult(this Exception ex) => ApiResult.CreateError(ex);
/// <summary>
/// Annotate Request DTOs with IGet, IPost, etc HTTP Verb markers to specify which HTTP Method is used:
/// https://docs.servicestack.net/csharp-client.html#http-verb-interface-markers
/// </summary>
public static ApiResult<TResponse> Api<TResponse>(this IServiceClient client, IReturn<TResponse> request)
{
try
{
var result = client.Send(request);
return ApiResult.Create(result);
}
catch (Exception ex)
{
return ex.ToApiResult<TResponse>();
}
}
/// <summary>
/// Annotate Request DTOs with IGet, IPost, etc HTTP Verb markers to specify which HTTP Method is used:
/// https://docs.servicestack.net/csharp-client.html#http-verb-interface-markers
/// </summary>
public static async Task<ApiResult<TResponse>> ApiAsync<TResponse>(this IServiceClient client,
IReturn<TResponse> request)
{
try
{
var result = await client.SendAsync(request).ConfigAwait();
return ApiResult.Create(result);
}
catch (Exception ex)
{
return ex.ToApiResult<TResponse>();
}
}
/// <summary>
/// Annotate Request DTOs with IGet, IPost, etc HTTP Verb markers to specify which HTTP Method is used:
/// https://docs.servicestack.net/csharp-client.html#http-verb-interface-markers
/// </summary>
public static ApiResult<EmptyResponse> Api(this IServiceClient client, IReturnVoid request)
{
try
{
client.Send(request);
return ApiResult.Create(new EmptyResponse());
}
catch (Exception ex)
{
return ex.ToApiResult();
}
}
/// <summary>
/// Annotate Request DTOs with IGet, IPost, etc HTTP Verb markers to specify which HTTP Method is used:
/// https://docs.servicestack.net/csharp-client.html#http-verb-interface-markers
/// </summary>
public static async Task<ApiResult<EmptyResponse>> ApiAsync(this IServiceClient client, IReturnVoid request)
{
try
{
await client.SendAsync(request).ConfigAwait();
return ApiResult.Create(new EmptyResponse());
}
catch (Exception ex)
{
return ex.ToApiResult();
}
}
/// <summary>
/// Convert AutoLogin RegisterResponse into AuthenticateResponse to avoid additional trip
/// </summary>
public static AuthenticateResponse ToAuthenticateResponse(this RegisterResponse from) => new() {
// don't use automapping/reflection as needs to work in AOT/Blazor
UserId = from.UserId,
SessionId = from.SessionId,
UserName = from.UserName,
ReferrerUrl = from.ReferrerUrl,
BearerToken = from.BearerToken,
RefreshToken = from.RefreshToken,
Roles = from.Roles,
Permissions = from.Permissions,
Meta = from.Meta,
};
}