| | 1 | | using Microsoft.EntityFrameworkCore; |
| | 2 | |
|
| | 3 | | namespace NLightning.Infrastructure.Repositories.Database.Node; |
| | 4 | |
|
| | 5 | | using Domain.Crypto.ValueObjects; |
| | 6 | | using Domain.Node.Interfaces; |
| | 7 | | using Domain.Node.Models; |
| | 8 | | using Persistence.Contexts; |
| | 9 | | using Persistence.Entities.Node; |
| | 10 | |
|
| | 11 | | public class PeerDbRepository : BaseDbRepository<PeerEntity>, IPeerDbRepository |
| | 12 | | { |
| 0 | 13 | | public PeerDbRepository(NLightningDbContext context) : base(context) |
| 0 | 14 | | { |
| 0 | 15 | | } |
| | 16 | |
|
| | 17 | | public async Task AddOrUpdateAsync(PeerModel peerModel) |
| 0 | 18 | | { |
| 0 | 19 | | var peerEntity = MapDomainToEntity(peerModel); |
| | 20 | |
|
| 0 | 21 | | var existingEntity = await GetByIdAsync(peerEntity.NodeId); |
| 0 | 22 | | if (existingEntity is null) |
| 0 | 23 | | { |
| 0 | 24 | | Insert(peerEntity); |
| 0 | 25 | | } |
| | 26 | | else |
| 0 | 27 | | { |
| 0 | 28 | | Update(peerEntity); |
| 0 | 29 | | } |
| 0 | 30 | | } |
| | 31 | |
|
| | 32 | | public void Update(PeerModel peerModel) |
| 0 | 33 | | { |
| 0 | 34 | | var peerEntity = MapDomainToEntity(peerModel); |
| 0 | 35 | | base.Update(peerEntity); |
| 0 | 36 | | } |
| | 37 | |
|
| | 38 | | public async Task<IEnumerable<PeerModel>> GetAllAsync() |
| 0 | 39 | | { |
| 0 | 40 | | var peerEntities = await Get().ToListAsync(); |
| | 41 | |
|
| 0 | 42 | | return peerEntities.Select(MapEntityToDomain); |
| 0 | 43 | | } |
| | 44 | |
|
| | 45 | | public async Task<PeerModel?> GetByNodeIdAsync(CompactPubKey nodeId) |
| 0 | 46 | | { |
| 0 | 47 | | var peerEntity = await GetByIdAsync(nodeId); |
| 0 | 48 | | if (peerEntity == null) |
| 0 | 49 | | return null; |
| | 50 | |
|
| 0 | 51 | | return MapEntityToDomain(peerEntity); |
| 0 | 52 | | } |
| | 53 | |
|
| | 54 | | public async Task UpdatePeerLastSeenAsync(CompactPubKey peerCompactPubKey) |
| 0 | 55 | | { |
| 0 | 56 | | var existingPeer = await GetByIdAsync(peerCompactPubKey); |
| 0 | 57 | | if (existingPeer is not null) |
| 0 | 58 | | { |
| 0 | 59 | | existingPeer.LastSeenAt = DateTime.UtcNow; |
| 0 | 60 | | Update(existingPeer); |
| 0 | 61 | | } |
| 0 | 62 | | } |
| | 63 | |
|
| | 64 | | private static PeerEntity MapDomainToEntity(PeerModel peerModel) |
| 0 | 65 | | { |
| 0 | 66 | | return new PeerEntity |
| 0 | 67 | | { |
| 0 | 68 | | NodeId = peerModel.NodeId, |
| 0 | 69 | | Host = peerModel.Host, |
| 0 | 70 | | Port = peerModel.Port, |
| 0 | 71 | | LastSeenAt = peerModel.LastSeenAt |
| 0 | 72 | | }; |
| 0 | 73 | | } |
| | 74 | |
|
| | 75 | | private static PeerModel MapEntityToDomain(PeerEntity peerEntity) |
| 0 | 76 | | { |
| 0 | 77 | | return new PeerModel(peerEntity.NodeId, peerEntity.Host, peerEntity.Port) |
| 0 | 78 | | { |
| 0 | 79 | | LastSeenAt = peerEntity.LastSeenAt |
| 0 | 80 | | }; |
| 0 | 81 | | } |
| | 82 | | } |