Template
Initial Commit
This commit is contained in:
commit
bd7e505432
22 files changed
+871
No files matched your search
@@ -0,0 +1,52 @@
|
||||
using AutoMapper;
|
||||
using RT.Domain.Entities;
|
||||
using RT.Infrastructure.Repositories;
|
||||
|
||||
namespace RT.Application.Services;
|
||||
|
||||
public abstract class Service<TEntity, TCreate, TUpdate, TResponse>(
|
||||
IRepository<TEntity> repository,
|
||||
IMapper mapper)
|
||||
: IService<TCreate, TUpdate, TResponse>
|
||||
where TEntity : BaseEntity
|
||||
{
|
||||
protected readonly IRepository<TEntity> Repository = repository;
|
||||
protected readonly IMapper Mapper = mapper;
|
||||
|
||||
public virtual async Task<IEnumerable<TResponse>> GetAllAsync(CancellationToken ct = default)
|
||||
{
|
||||
var entities = await Repository.GetAllAsync(ct);
|
||||
return Mapper.Map<IEnumerable<TResponse>>(entities);
|
||||
}
|
||||
|
||||
public virtual async Task<TResponse?> GetByIdAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
var entity = await Repository.GetByIdAsync(id, ct);
|
||||
return entity is null ? default : Mapper.Map<TResponse>(entity);
|
||||
}
|
||||
|
||||
public virtual async Task<TResponse> CreateAsync(TCreate dto, CancellationToken ct = default)
|
||||
{
|
||||
var entity = Mapper.Map<TEntity>(dto);
|
||||
await Repository.InsertAsync(entity, ct);
|
||||
return Mapper.Map<TResponse>(entity);
|
||||
}
|
||||
|
||||
public virtual async Task<TResponse> UpdateAsync(Guid id, TUpdate dto, CancellationToken ct = default)
|
||||
{
|
||||
var entity = await Repository.GetByIdAsync(id, ct)
|
||||
?? throw new KeyNotFoundException($"{typeof(TEntity).Name} {id} not found.");
|
||||
|
||||
Mapper.Map(dto, entity);
|
||||
await Repository.UpdateAsync(entity, ct);
|
||||
return Mapper.Map<TResponse>(entity);
|
||||
}
|
||||
|
||||
public virtual async Task DeleteAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
var entity = await Repository.GetByIdAsync(id, ct)
|
||||
?? throw new KeyNotFoundException($"{typeof(TEntity).Name} {id} not found.");
|
||||
|
||||
await Repository.RemoveAsync(entity, ct);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user