Skip to content

Instantly share code, notes, and snippets.

@dario-l
Created September 29, 2015 10:53
Show Gist options
  • Save dario-l/4322e0a83c9f7343b740 to your computer and use it in GitHub Desktop.
Save dario-l/4322e0a83c9f7343b740 to your computer and use it in GitHub Desktop.
public static class ModuleHandleExtensions
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public static object Handle<T>(
this NancyModule m,
Action<T> handle,
Func<T, object> successResult,
Func<T, object> failureResult = null)
{
if (successResult == null) throw new Exception("Result not set");
if (failureResult == null) failureResult = successResult;
var model = m.Bind<T>();
if (logger.IsTraceEnabled)
{
logger.Trace("Executing {0}: {1}".Fmt(m.Request.Url, JsonConvert.SerializeObject(model)));
}
try
{
handle(model);
return successResult(model);
}
catch (ValidationException ex)
{
m.ModelValidationResult = CreateValidationResult(ex);
return failureResult(model);
}
}
public static object Handle<T, TR>(
this NancyModule m,
Func<T, TR> handle,
Func<T, TR, object> successResult,
Func<T, TR, object> failureResult = null)
{
if (successResult == null) throw new Exception("Result not set");
if (failureResult == null) failureResult = successResult;
var model = m.Bind<T>();
if (logger.IsTraceEnabled)
{
logger.Trace("Executing {0}: {1}".Fmt(m.Request.Url, JsonConvert.SerializeObject(model)));
}
try
{
var result = handle(model);
return successResult(model, result);
}
catch (ValidationException ex)
{
m.ModelValidationResult = CreateValidationResult(ex);
return failureResult(model, default(TR));
}
}
private static ModelValidationResult CreateValidationResult(ValidationException ex)
{
var errors = GetErrors(ex.Errors);
return new ModelValidationResult(errors);
}
private static IEnumerable<ModelValidationError> GetErrors(IEnumerable<ValidationFailure> errors)
{
return errors.Select(error => new ModelValidationError(new[] { error.PropertyName }, error.ErrorMessage));
}
}
public class LoginModule : NancyModule
{
public LoginModule(IMediator mediator)
{
Get["/login"] = _ => View["login"];
Post["/login"] = _ => this.Handle<Login.Model, Guid>(
mediator.Send,
(m, r) => this.LoginAndRedirect(r),
(m, r) => View["login", m]);
Get["/logout"] = _ => this.LogoutAndRedirect("~/");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment