Centralize stored procedure SQL generation in StoredProcedureBuilder, allowing handlers to specify procedure name and return variable. Removes manual SQL string building from DeleteObjectProcedure and UpdateObjectProcedure handlers, reducing boilerplate and improving maintainability.
64 lines
2.0 KiB
C#
64 lines
2.0 KiB
C#
using DigitalData.Core.Abstraction.Application.Repository;
|
|
using DigitalData.Core.Exceptions;
|
|
using MediatR;
|
|
using Microsoft.Data.SqlClient;
|
|
using Microsoft.Extensions.Options;
|
|
using ReC.Application.Common.Exceptions;
|
|
using ReC.Application.Common.Options;
|
|
|
|
namespace ReC.Application.Common.Procedures.DeleteProcedure;
|
|
|
|
public record DeleteObjectProcedure : IRequest<int>
|
|
{
|
|
/// <summary>
|
|
/// Target entity: ACTION, ENDPOINT, ENDPOINT_AUTH, ENDPOINT_PARAMS, PROFILE, RESULT
|
|
/// </summary>
|
|
public string Entity { get; set; } = null!;
|
|
|
|
/// <summary>
|
|
/// Start GUID/ID (inclusive)
|
|
/// </summary>
|
|
public long Start { get; set; }
|
|
|
|
/// <summary>
|
|
/// End GUID/ID (inclusive). If 0, will be set to Start value.
|
|
/// </summary>
|
|
public long End { get; set; }
|
|
|
|
/// <summary>
|
|
/// If true, delete even if dependent data exists
|
|
/// </summary>
|
|
public bool Force { get; set; }
|
|
}
|
|
|
|
public class DeleteObjectProcedureHandler(IRepository repo, IOptionsMonitor<SqlExceptionOptions> sqlExOpt) : IRequestHandler<DeleteObjectProcedure, int>
|
|
{
|
|
public async Task<int> Handle(DeleteObjectProcedure request, CancellationToken cancel)
|
|
{
|
|
var sp = new StoredProcedureBuilder("[dbo].[PRREC_DELETE_OBJECT]", "RC")
|
|
.Add("pENTITY", request.Entity)
|
|
.Add("pSTART", request.Start.ToString())
|
|
.Add("pEND", request.End.ToString())
|
|
.Add("pFORCE", request.Force);
|
|
|
|
try
|
|
{
|
|
var result = await repo.ExecuteQueryRawAsync(sp.BuildSql(), sp.BuildParameters(), cancel);
|
|
|
|
if (result > 0)
|
|
{
|
|
throw new DeleteObjectFailedException(request, $"DeleteObject stored procedure failed with error code: {result}");
|
|
}
|
|
|
|
return result;
|
|
}
|
|
catch (SqlException ex)
|
|
{
|
|
if (sqlExOpt.CurrentValue.BadRequestSqlExceptionNumbers.Contains(ex.Number))
|
|
throw new BadRequestException(ex.Message, ex);
|
|
else
|
|
throw;
|
|
}
|
|
}
|
|
}
|