using Microsoft.AspNetCore.Mvc.Filters;
using SqlSugar;

namespace OpenAuth.WebApi.Model
{
    public class TransactionFilter : IActionFilter
    {
        ISqlSugarClient _db;
        public TransactionFilter(ISqlSugarClient db)
        {
            _db = db;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            _db.AsTenant().BeginTran();
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception == null)
            {
                _db.AsTenant().CommitTran();
            }
            else
            {
                _db.AsTenant().RollbackTran();
            }
        }
    }
}
