Created
August 28, 2021 01:03
-
-
Save flakey-bit/32d5e9e1ba3c8fc802bfb9faf15e09fe to your computer and use it in GitHub Desktop.
Fluent, immutable builder for ValidationProblemDetails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class ValidationProblemDetailsBuilder | |
{ | |
private readonly List<Action<ModelStateDictionary>> _modelStateActions; | |
private readonly List<Action<ValidationProblemDetails>> _problemActions; | |
public ValidationProblemDetailsBuilder(): this (Array.Empty<Action<ModelStateDictionary>>(), Array.Empty<Action<ValidationProblemDetails>>()) | |
{ | |
} | |
private ValidationProblemDetailsBuilder(IEnumerable<Action<ModelStateDictionary>> modelStateActions, IEnumerable<Action<ValidationProblemDetails>> problemActions) | |
{ | |
_modelStateActions = new List<Action<ModelStateDictionary>>(modelStateActions); | |
_problemActions = new List<Action<ValidationProblemDetails>>(problemActions); | |
} | |
public ValidationProblemDetails Build() | |
{ | |
var modelState = new ModelStateDictionary(); | |
foreach (var action in _modelStateActions) | |
{ | |
action(modelState); | |
} | |
var problemDetails = new ValidationProblemDetails(modelState); | |
foreach (var action in _problemActions) | |
{ | |
action(problemDetails); | |
} | |
return problemDetails; | |
} | |
public ValidationProblemDetailsBuilder WithStatusCode(HttpStatusCode statusCode) => | |
AddAction(problemDetails => problemDetails.Status = (int) statusCode); | |
public ValidationProblemDetailsBuilder WithModelError(string key, string modelError) => | |
AddAction(modelState => modelState.AddModelError(key, modelError)); | |
// Since this is an immutable builder, concatenate the action when constructing the new builder | |
private ValidationProblemDetailsBuilder AddAction(Action<ValidationProblemDetails> action) => new(_modelStateActions, _problemActions.Concat(new[] {action})); | |
// Since this is an immutable builder, concatenate the action when constructing the new builder | |
private ValidationProblemDetailsBuilder AddAction(Action<ModelStateDictionary> action) => new(_modelStateActions.Concat(new[] {action}), _problemActions); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment