-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #62 from argon-chat/feature/interceptors
Add timestamp and soft delete interceptor
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
65 changes: 65 additions & 0 deletions
65
src/Argon.Api/Features/EF/TimeStampAndSoftDeleteInterceptor.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
namespace Argon.Api.Features.EF; | ||
|
||
using Contracts.Models; | ||
using Microsoft.EntityFrameworkCore.Diagnostics; | ||
using Microsoft.EntityFrameworkCore; | ||
|
||
public class TimeStampAndSoftDeleteInterceptor : SaveChangesInterceptor | ||
{ | ||
public override InterceptionResult<int> SavingChanges( | ||
DbContextEventData eventData, | ||
InterceptionResult<int> result) | ||
{ | ||
HandleSoftDelete(eventData.Context); | ||
SetTimestamps(eventData.Context); | ||
return base.SavingChanges(eventData, result); | ||
} | ||
|
||
public override ValueTask<InterceptionResult<int>> SavingChangesAsync( | ||
DbContextEventData eventData, | ||
InterceptionResult<int> result, | ||
CancellationToken cancellationToken = default) | ||
{ | ||
HandleSoftDelete(eventData.Context); | ||
SetTimestamps(eventData.Context); | ||
return base.SavingChangesAsync(eventData, result, cancellationToken); | ||
} | ||
|
||
private void SetTimestamps(DbContext? context) | ||
{ | ||
if (context == null) return; | ||
|
||
var entries = context.ChangeTracker | ||
.Entries() | ||
.Where(e => e is { Entity: ArgonEntity, State: EntityState.Added or EntityState.Modified }); | ||
|
||
foreach (var entry in entries) | ||
{ | ||
var entity = (ArgonEntity)entry.Entity; | ||
|
||
if (entry.State == EntityState.Added) | ||
entity.CreatedAt = DateTime.UtcNow; | ||
|
||
entity.UpdatedAt = DateTime.UtcNow; | ||
} | ||
} | ||
|
||
private void HandleSoftDelete(DbContext? context) | ||
{ | ||
if (context == null) return; | ||
|
||
var entries = context.ChangeTracker | ||
.Entries() | ||
.Where(e => e is { Entity: ArgonEntity, State: EntityState.Deleted }); | ||
|
||
foreach (var entry in entries) | ||
{ | ||
var entity = (ArgonEntity)entry.Entity; | ||
|
||
entity.DeletedAt = DateTime.UtcNow; | ||
entity.IsDeleted = true; | ||
|
||
entry.State = EntityState.Modified; | ||
} | ||
} | ||
} |