forked from ardalis/Result
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResultStatusMap.cs
More file actions
257 lines (218 loc) · 10.3 KB
/
ResultStatusMap.cs
File metadata and controls
257 lines (218 loc) · 10.3 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
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace Ardalis.Result.AspNetCore
{
/// <summary>
/// A map of <see cref="ResultStatus"/>es to <see cref="HttpStatusCode"/>s combined with other configuration
/// </summary>
public class ResultStatusMap
{
private readonly Dictionary<ResultStatus, ResultStatusOptions> _map = new Dictionary<ResultStatus, ResultStatusOptions>();
internal ResultStatusMap()
{
}
public IEnumerable<ResultStatus> Keys => _map.Keys;
/// <summary>
/// Adds default mapping for all known <see cref="ResultStatus"/>es to <see cref="HttpStatusCode"/>s
/// </summary>
public ResultStatusMap AddDefaultMap()
{
return For(ResultStatus.Ok, HttpStatusCode.OK)
.For(ResultStatus.Error, (HttpStatusCode)422, resultStatusOptions => resultStatusOptions
.With(UnprocessableEntity))
.For(ResultStatus.Forbidden, HttpStatusCode.Forbidden)
.For(ResultStatus.Unauthorized, HttpStatusCode.Unauthorized)
.For(ResultStatus.Invalid, HttpStatusCode.BadRequest, resultStatusOptions => resultStatusOptions
.With(BadRequest))
.For(ResultStatus.NotFound, HttpStatusCode.NotFound, resultStatusOptions => resultStatusOptions
.With(NotFoundEntity))
.For(ResultStatus.Conflict, HttpStatusCode.Conflict, resultStatusOptions => resultStatusOptions
.With(ConflictEntity))
.For(ResultStatus.CriticalError, HttpStatusCode.InternalServerError, resultStatusOptions =>
resultStatusOptions
.With(CriticalEntity))
.For(ResultStatus.Unavailable, HttpStatusCode.ServiceUnavailable, resultStatusOptions =>
resultStatusOptions
.With(UnavailableEntity))
.For(ResultStatus.NoContent, HttpStatusCode.NoContent);
}
/// <summary>
/// Maps <paramref name="status"/> to <paramref name="defaultStatusCode"/>.
/// Allows to override default status code for specific Http Methods
/// </summary>
/// <param name="status">Result Status to map.</param>
/// <param name="defaultStatusCode">Default Status Code.</param>
/// <param name="configure">A <see cref="Action"/> to configure Status Codes for specific Http Methods.</param>
public ResultStatusMap For(ResultStatus status, HttpStatusCode defaultStatusCode, Action<ResultStatusOptions> configure)
{
var info = new ResultStatusOptions(status, defaultStatusCode);
configure(info);
this[status] = info;
return this;
}
/// <summary>
/// Maps <paramref name="status"/> to <paramref name="statusCode"/>.
/// </summary>
/// <param name="status">Result Status to map.</param>
/// <param name="statusCode">Status Code.</param>
public ResultStatusMap For(ResultStatus status, HttpStatusCode statusCode)
{
this[status] = new ResultStatusOptions(status, statusCode);
return this;
}
/// <summary>
/// Remove mapping for <paramref name="status"/>
/// </summary>
/// <param name="status"></param>
public ResultStatusMap Remove(ResultStatus status)
{
_map.Remove(status);
return this;
}
/// <summary>
/// Determines whether there is a mapping for given <paramref name="status"/>
/// </summary>
/// <param name="status"></param>
/// <returns></returns>
public bool ContainsKey(ResultStatus status)
{
return _map.ContainsKey(status);
}
internal ResultStatusOptions this[ResultStatus status]
{
get { return _map[status]; }
set { _map[status] = value; }
}
private static ValidationProblemDetails BadRequest(ControllerBase controller, IResult result)
{
foreach (var error in result.ValidationErrors)
{
// TODO: mark ValidationError.Identifier as required and limit setting (see #179)
string identifier = error.Identifier ?? "(identifier)";
// TODO: mark ValidationError.Identifier as required and limit setting (see #179)
string errorMessage = error.ErrorMessage ?? "(error message)";
controller.ModelState.AddModelError(identifier, errorMessage);
}
return new ValidationProblemDetails(controller.ModelState);
}
private static ProblemDetails UnprocessableEntity(ControllerBase controller, IResult result)
{
var details = new StringBuilder("Next error(s) occurred:");
foreach (var error in result.Errors) details.Append("* ").Append(error).AppendLine();
return new ProblemDetails
{
Title = "Something went wrong.",
Detail = result.Errors.Any() ? details.ToString() : null
};
}
private static ProblemDetails NotFoundEntity(ControllerBase controller, IResult result)
{
var details = new StringBuilder("Next error(s) occurred:");
foreach (var error in result.Errors) details.Append("* ").Append(error).AppendLine();
return new ProblemDetails
{
Title = "Resource not found.",
Detail = result.Errors.Any() ? details.ToString() : null
};
}
private static ProblemDetails ConflictEntity(ControllerBase controller, IResult result)
{
var details = new StringBuilder("Next error(s) occurred:");
foreach (var error in result.Errors) details.Append("* ").Append(error).AppendLine();
return new ProblemDetails
{
Title = "There was a conflict.",
Detail = result.Errors.Any() ? details.ToString() : null
};
}
private static ProblemDetails CriticalEntity(ControllerBase controller, IResult result)
{
var details = new StringBuilder("Next error(s) occurred:");
foreach (var error in result.Errors) details.Append("* ").Append(error).AppendLine();
return new ProblemDetails
{
Title = "Something went wrong.",
Detail = result.Errors.Any() ? details.ToString() : null
};
}
private static ProblemDetails UnavailableEntity(ControllerBase controller, IResult result)
{
var details = new StringBuilder("Next error(s) occurred:");
foreach (var error in result.Errors) details.Append("* ").Append(error).AppendLine();
return new ProblemDetails
{
Title = "Service is unavailable.",
Detail = result.Errors.Any() ? details.ToString() : null
};
}
}
public class ResultStatusOptions
{
private readonly Dictionary<string, HttpStatusCode> _methodToStatusMap = new Dictionary<string, HttpStatusCode>();
private readonly HttpStatusCode _defaultStatusCode;
internal ResultStatusOptions(ResultStatus status, HttpStatusCode defaultStatusCode)
{
_defaultStatusCode = defaultStatusCode;
Status = status;
}
internal ResultStatusOptions(ResultStatus status, HttpStatusCode defaultStatusCode, Type responseType, Func<ControllerBase, IResult, object> getResponseObject)
{
_defaultStatusCode = defaultStatusCode;
Status = status;
ResponseType = responseType;
GetResponseObject = getResponseObject;
}
internal ResultStatus Status { get; }
internal Type ResponseType { get; private set; }
internal Func<ControllerBase, IResult, object> GetResponseObject { get; private set; }
/// <summary>
/// Gets Http Status Code for specific Http Method.
/// </summary>
/// <param name="method"></param>
/// <returns>Http Status Code for specific Http Method if configured, otherwise default Http Status Code.</returns>
public HttpStatusCode GetStatusCode(string method)
{
method = method?.ToLower();
if (string.IsNullOrEmpty(method) || !_methodToStatusMap.ContainsKey(method)) return _defaultStatusCode;
return _methodToStatusMap[method];
}
/// <summary>
/// Maps <paramref name="method"/> to a <paramref name="statusCode"/>
/// </summary>
/// <param name="method">Http Method.</param>
/// <param name="statusCode">Http Status Code.</param>
public ResultStatusOptions For(string method, HttpStatusCode statusCode)
{
_methodToStatusMap[method.ToLower()] = statusCode;
return this;
}
/// <summary>
/// Sets GetResponseObject callback.
/// </summary>
/// <param name="getResponseObject">A <see cref="Func"/> to extract response object from Result object for specific Result Status.</param>
public ResultStatusOptions With<T>(Func<ControllerBase, IResult, T> getResponseObject)
{
ResponseType = typeof(T);
GetResponseObject = (ctrlr, result) => getResponseObject(ctrlr, result);
return this;
}
/// <summary>
/// Sets GetResponseObject callback.
/// This overload may be useful when response object type is converted to different type before serialization.
/// For example, when returning <see cref="Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary"/>, <see cref="IDictionary{string, string[]}"/> is actually serialized.
/// </summary>
/// <param name="responseType">Response Type.</param>
/// <param name="getResponseObject">A <see cref="Func"/> to extract response object from Result object for specific Result Status.</param>
/// <returns></returns>
public ResultStatusOptions With(Type responseType, Func<ControllerBase, IResult, object> getResponseObject)
{
ResponseType = responseType;
GetResponseObject = getResponseObject;
return this;
}
}
}