using System; using MongoDB.Driver; using PolyTraderSharp.Extensions; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using PolyTraderSharp.Models; namespace PolyTraderSharp.Extensions { public static class MongoDbLiteDBShim { // 1. LiteDB: FindOne(predicate) -> MongoDB: Find(predicate).FirstOrDefault() public static T LiteFindOne(this IMongoCollection col, Expression> predicate) { return col.Find(predicate).FirstOrDefault(); } // 2. LiteDB: Find(predicate) -> MongoDB: Find(predicate).ToList() // Note: LiteDB returns IEnumerable. ToList() is perfectly fine for iteration. public static List LiteFind(this IMongoCollection col, Expression> predicate) { return col.Find(predicate).ToList(); } // 3. LiteDB: FindAll() -> MongoDB: Find(_ => true).ToList() public static List LiteFindAll(this IMongoCollection col) { return col.Find(_ => true).ToList(); } // 4. Upsert extensions mapped to Primary Keys public static void Upsert(this IMongoCollection col, AccountState doc) { col.ReplaceOne(x => x.AccountId == doc.AccountId, doc, new ReplaceOptions { IsUpsert = true }); } public static void Upsert(this IMongoCollection col, TrackedTrader doc) { col.ReplaceOne(x => x.Id == doc.Id, doc, new ReplaceOptions { IsUpsert = true }); } public static void Upsert(this IMongoCollection col, Position doc) { col.ReplaceOne(x => x.TokenId == doc.TokenId, doc, new ReplaceOptions { IsUpsert = true }); } public static void Upsert(this IMongoCollection col, MarketData doc) { col.ReplaceOne(x => x.Id == doc.Id, doc, new ReplaceOptions { IsUpsert = true }); } // 5. Update (Updates without upserting if it doesn't exist) public static void Update(this IMongoCollection col, TrackedTrader doc) { col.ReplaceOne(x => x.Id == doc.Id, doc); } public static void Update(this IMongoCollection col, AccountState doc) { col.ReplaceOne(x => x.AccountId == doc.AccountId, doc); } public static void Update(this IMongoCollection col, MarketData doc) { col.ReplaceOne(x => x.Id == doc.Id, doc); } // 6. Insert maps perfectly to InsertOne public static void Insert(this IMongoCollection col, T doc) { col.InsertOne(doc); } // 7. Delete (by TokenId / String ID) public static void Delete(this IMongoCollection col, string tokenId) { col.DeleteOne(x => x.TokenId == tokenId); } // 8. EnsureIndex shim (MongoDB Index Creation) public static void EnsureIndex(this IMongoCollection col, Expression> property) { try { var indexKeys = Builders.IndexKeys.Ascending(property); var indexModel = new CreateIndexModel(indexKeys); col.Indexes.CreateOne(indexModel); } catch { } } } }