| | 1 | | using Bookings.Domain; |
| | 2 | | using System.Collections.Concurrent; |
| | 3 | |
|
| | 4 | | namespace Bookings.Api.Bookings |
| | 5 | | { |
| | 6 | | public class BookingsInMemRepository : IBookingsRepository |
| | 7 | | { |
| 54 | 8 | | private readonly ConcurrentDictionary<Guid, Booking> _store = new(); |
| 18 | 9 | | private readonly ConcurrentDictionary<BookingKey, Guid> _lookup = new(); |
| 4056 | 10 | |
|
| | 11 | | public KeyValuePair<Guid, Booking?> Create(Booking booking) |
| 6085 | 12 | | { |
| 2029 | 13 | | var bookingKey = BookingKey.From(booking); |
| 4056 | 14 | |
|
| 6085 | 15 | | var id = _lookup.AddOrUpdate( |
| 6085 | 16 | | bookingKey, |
| 6082 | 17 | | key => Guid.NewGuid(), |
| 2032 | 18 | | (key, value) => value); |
| 4056 | 19 | |
|
| 6085 | 20 | | var stored = _store.AddOrUpdate( |
| 2029 | 21 | | id, |
| 2026 | 22 | | key => booking, |
| 2040 | 23 | | (key, value) => value); |
| 8 | 24 | |
|
| 2037 | 25 | | return new(id, stored); |
| 2029 | 26 | | } |
| | 27 | |
|
| 6016 | 28 | | public KeyValuePair<Guid, Booking?> Update(Guid id, Booking booking) |
| 7020 | 29 | | { |
| 7020 | 30 | | if (!_store.ContainsKey(id)) |
| 6016 | 31 | | return new(id, null); |
| | 32 | |
|
| 1004 | 33 | | if (_store.TryGetValue(id, out var existing) && Equals(existing, booking)) |
| 2010 | 34 | | return new(id, existing); |
| 2008 | 35 | |
|
| 3010 | 36 | | var updated = _store.AddOrUpdate( |
| 1002 | 37 | | id, |
| 6943 | 38 | | key => booking, |
| 2978 | 39 | | (key, value) => booking); |
| 2008 | 40 | |
|
| 3010 | 41 | | var newKey = BookingKey.From(updated); |
| 1002 | 42 | | _lookup.AddOrUpdate( |
| 1002 | 43 | | newKey, |
| 3010 | 44 | | key => id, |
| 3010 | 45 | | (key, value) => id); |
| 2008 | 46 | |
|
| 3010 | 47 | | return new(id, updated); |
| 1004 | 48 | | } |
| | 49 | |
|
| | 50 | | public Dictionary<Guid, Booking> GetAll() |
| 5 | 51 | | { |
| 5 | 52 | | return _store.ToDictionary(); // Snapshot |
| 5 | 53 | | } |
| | 54 | |
|
| | 55 | | public KeyValuePair<Guid, Booking?> Get(Guid id) |
| 3008 | 56 | | { |
| 3008 | 57 | | _store.TryGetValue(id, out var found); |
| 3008 | 58 | | return new(id, found); |
| 3008 | 59 | | } |
| | 60 | |
|
| | 61 | | public KeyValuePair<Guid, Booking?> Delete(Guid id) |
| 1004 | 62 | | { |
| 1004 | 63 | | _store.TryRemove(id, out var deleted); |
| | 64 | |
|
| 1004 | 65 | | if (deleted != null) |
| 1004 | 66 | | _lookup.TryRemove(BookingKey.From(deleted), out var removedId); |
| | 67 | |
|
| 1004 | 68 | | return new(id, deleted); |
| 1004 | 69 | | } |
| | 70 | | } |
| | 71 | | } |