using LocationsApi.Models; using MongoDB.Driver; namespace LocationsApi.Services; public class LocationStore { private readonly IMongoCollection _col; public LocationStore(IConfiguration cfg) { var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017"; var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb"; var client = new MongoClient(cs); var db = client.GetDatabase(dbName); _col = db.GetCollection("Locations"); var ownerIndex = Builders.IndexKeys.Ascending(l => l.OwnerUserId); _col.Indexes.CreateOne(new CreateIndexModel(ownerIndex)); } public Task CreateAsync(Location location) => _col.InsertOneAsync(location); public Task> GetForOwnerAsync(string ownerUserId) => _col.Find(l => l.OwnerUserId == ownerUserId).ToListAsync(); public async Task DeleteForOwnerAsync(string id, string ownerUserId, bool allowAnyOwner) { var filter = Builders.Filter.Eq(l => l.Id, id); if (!allowAnyOwner) { filter = Builders.Filter.And( filter, Builders.Filter.Eq(l => l.OwnerUserId, ownerUserId) ); } var result = await _col.DeleteOneAsync(filter); return result.DeletedCount > 0; } public async Task UpdateNameAsync(string id, string name) { var filter = Builders.Filter.Eq(l => l.Id, id); var update = Builders.Update.Set(l => l.Name, name); var result = await _col.UpdateOneAsync(filter, update); return result.ModifiedCount > 0; } }