Skip to content

Instantly share code, notes, and snippets.

@bruceharrison1984
Last active September 5, 2019 03:53
Show Gist options
  • Save bruceharrison1984/e5a6aa726ce726b15958f29267bd9385 to your computer and use it in GitHub Desktop.
Save bruceharrison1984/e5a6aa726ce726b15958f29267bd9385 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using FluentValidation;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.Extensions.Logging;
using WidgetApi.Models;
namespace WidgetApi.FunctionHelpers
{
public class FunctionWrapper<T> where T : ModelBase
{
private readonly BaseValidator<T> _validator;
private readonly ILogger _log;
public FunctionWrapper(BaseValidator<T> validator, ILogger<FunctionWrapper<T>> log)
{
_validator = validator;
_log = log;
}
public async Task<IActionResult> Execute(T model, HttpRequest req, Func<Task<IActionResult>> azureFunction)
{
var results = await _validator.ValidateAsync(model, ruleSet: $"default,audit,{req.Method}");
if (!results.IsValid)
{
var errors = results.Errors.Select(x => x.ErrorMessage).ToList();
_log.LogWarning($"Model validation failed for type '{typeof(T).Name}'. Validation errors: [{errors.Join()}] ");
return new ResponseEnvelopeResult<T>(HttpStatusCode.BadRequest, null, errors);
}
try
{
return await azureFunction();
}
catch (Exception e)
{
_log.LogError(e, "Unhandled exception occured in FunctionWrapper");
return new ResponseEnvelopeResult<T>(HttpStatusCode.InternalServerError, null, new[] { e.Message });
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment