/
ElasticSearchRepository.cs
47 lines (38 loc) · 1.64 KB
/
ElasticSearchRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using Core.ElasticSearch.Indices;
using Nest;
using IAggregate = Core.Aggregates.IAggregate;
namespace Core.ElasticSearch.Repository;
public interface IElasticSearchRepository<T> where T : class, IAggregate, new()
{
Task<T?> Find(Guid id, CancellationToken cancellationToken);
Task Add(T aggregate, CancellationToken cancellationToken);
Task Update(T aggregate, CancellationToken cancellationToken);
Task Delete(T aggregate, CancellationToken cancellationToken);
}
public class ElasticSearchRepository<T>: IElasticSearchRepository<T> where T : class, IAggregate, new()
{
private readonly IElasticClient elasticClient;
public ElasticSearchRepository(
IElasticClient elasticClient
)
{
this.elasticClient = elasticClient ?? throw new ArgumentNullException(nameof(elasticClient));
}
public async Task<T?> Find(Guid id, CancellationToken cancellationToken)
{
var response = await elasticClient.GetAsync<T>(id, ct: cancellationToken).ConfigureAwait(false);
return response?.Source;
}
public Task Add(T aggregate, CancellationToken cancellationToken)
{
return elasticClient.IndexAsync(aggregate, i => i.Id(aggregate.Id).Index(IndexNameMapper.ToIndexName<T>()), cancellationToken);
}
public Task Update(T aggregate, CancellationToken cancellationToken)
{
return elasticClient.UpdateAsync<T>(aggregate.Id, i => i.Doc(aggregate).Index(IndexNameMapper.ToIndexName<T>()), cancellationToken);
}
public Task Delete(T aggregate, CancellationToken cancellationToken)
{
return elasticClient.DeleteAsync<T>(aggregate.Id, ct: cancellationToken);
}
}