Skip to content

Commit

Permalink
[MTGOSDK/API/Collection] CollectionManager: Cache card accesses by ID
Browse files Browse the repository at this point in the history
  • Loading branch information
Qonfused committed Dec 27, 2023
1 parent 9624b00 commit 1f9a365
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
2 changes: 2 additions & 0 deletions MTGOSDK/src/API/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Security;
using System.Security.Authentication;

using MTGOSDK.API.Collection;
using MTGOSDK.API.Users;
using MTGOSDK.API.Interface;
using MTGOSDK.Core;
Expand Down Expand Up @@ -180,6 +181,7 @@ public Client(ClientOptions options = default) : base(
public void ClearCaches()
{
UserManager.Users.Clear();
CollectionManager.Cards.Clear();
}

/// <summary>
Expand Down
21 changes: 17 additions & 4 deletions MTGOSDK/src/API/Collection/CollectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
SPDX-License-Identifier: Apache-2.0
**/

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;

Expand Down Expand Up @@ -33,6 +34,11 @@ public static class CollectionManager
// ICardDefinition wrapper methods
//

/// <summary>
/// A dictionary of cached Card objects.
/// </summary>
public static ConcurrentDictionary<int, Card> Cards { get; } = new();

/// <summary>
/// Returns a list of catalog ids for the given card name.
/// </summary>
Expand All @@ -49,12 +55,19 @@ public static IList<int> GetCardIds(string cardName) =>
/// <exception cref="KeyNotFoundException">
/// Thrown if no card is found with the given catalog id.
/// </exception>
public static Card GetCard(int id) =>
new(
s_cardDataManager.GetCardDefinitionForCatId(id)
public static Card GetCard(int id)
{
if (!Cards.TryGetValue(id, out var card))
{
Cards[id] = card = new Card(
s_cardDataManager.GetCardDefinitionForCatId(id)
?? throw new KeyNotFoundException(
$"No card found with catalog id #{id}.")
);
);
}

return card;
}

/// <summary>
/// Returns a card object by the given card name.
Expand Down

0 comments on commit 1f9a365

Please sign in to comment.