using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using MongoDB.Driver; using StardewModdingAPI.Toolkit.Framework.Clients.Wiki; namespace StardewModdingAPI.Web.Framework.Caching.Wiki { /// Manages cached wiki data in MongoDB. internal class WikiCacheMongoRepository : BaseCacheRepository, IWikiCacheRepository { /********* ** Fields *********/ /// The collection for wiki metadata. private readonly IMongoCollection Metadata; /// The collection for wiki mod data. private readonly IMongoCollection Mods; /********* ** Public methods *********/ /// Construct an instance. /// The authenticated MongoDB database. public WikiCacheMongoRepository(IMongoDatabase database) { // get collections this.Metadata = database.GetCollection("wiki-metadata"); this.Mods = database.GetCollection("wiki-mods"); // add indexes if needed this.Mods.Indexes.CreateOne(new CreateIndexModel(Builders.IndexKeys.Ascending(p => p.ID))); } /// Get the cached wiki metadata. /// The fetched metadata. public bool TryGetWikiMetadata(out CachedWikiMetadata metadata) { metadata = this.Metadata.Find("{}").FirstOrDefault(); return metadata != null; } /// Get the cached wiki mods. /// A filter to apply, if any. public IEnumerable GetWikiMods(Expression> filter = null) { return filter != null ? this.Mods.Find(filter).ToList() : this.Mods.Find("{}").ToList(); } /// Save data fetched from the wiki compatibility list. /// The current stable Stardew Valley version. /// The current beta Stardew Valley version. /// The mod data. /// The stored metadata record. /// The stored mod records. public void SaveWikiData(string stableVersion, string betaVersion, IEnumerable mods, out CachedWikiMetadata cachedMetadata, out CachedWikiMod[] cachedMods) { cachedMetadata = new CachedWikiMetadata(stableVersion, betaVersion); cachedMods = mods.Select(mod => new CachedWikiMod(mod)).ToArray(); this.Mods.DeleteMany("{}"); this.Mods.InsertMany(cachedMods); this.Metadata.DeleteMany("{}"); this.Metadata.InsertOne(cachedMetadata); } } }