70 lines
2.5 KiB
C#
70 lines
2.5 KiB
C#
using System.Threading.Tasks;
|
|
using GameAuthApi.Models;
|
|
using Microsoft.Extensions.Configuration;
|
|
using MongoDB.Bson;
|
|
using MongoDB.Driver;
|
|
|
|
namespace GameAuthApi.Services;
|
|
|
|
public class LocationService
|
|
{
|
|
private readonly IMongoCollection<Location> _locations;
|
|
|
|
public LocationService(IConfiguration config)
|
|
{
|
|
var client = new MongoClient(config["MongoDB:ConnectionString"]);
|
|
var db = client.GetDatabase(config["MongoDB:DatabaseName"]);
|
|
_locations = db.GetCollection<Location>("Locations");
|
|
}
|
|
|
|
public virtual async Task<Location> GetByIdAsync(string id)
|
|
{
|
|
if (!ObjectId.TryParse(id, out _))
|
|
return null; // prevent crash if id is invalid
|
|
|
|
return await _locations.Find(x => x.Id == id).FirstOrDefaultAsync();
|
|
}
|
|
|
|
public virtual async Task CreateAsync(Location loc) =>
|
|
await _locations.InsertOneAsync(loc);
|
|
|
|
public virtual async Task DeleteAsync(string id) =>
|
|
await _locations.DeleteOneAsync(loc => loc.Id == id);
|
|
public virtual async Task UpdateAsync(Location loc) =>
|
|
await _locations.ReplaceOneAsync(l => l.Id == loc.Id, loc);
|
|
|
|
public virtual async Task AddPlayerToLocationAsync(string locationId, string playerId)
|
|
{
|
|
var update = Builders<Location>.Update.AddToSet(l => l.Players, playerId);
|
|
await _locations.UpdateOneAsync(l => l.Id == locationId, update);
|
|
}
|
|
|
|
public virtual async Task<Location> GetByCoordinatesAsync(int x, int y, int z)
|
|
{
|
|
return await _locations.Find(loc => loc.X == x && loc.Y == y && loc.Z == z).FirstOrDefaultAsync();
|
|
}
|
|
|
|
public virtual async Task<Location> GetSpawnLocationAsync()
|
|
{
|
|
return await _locations.Find(loc => loc.X == 0 && loc.Y == 0).FirstOrDefaultAsync();
|
|
}
|
|
|
|
public virtual async Task RemovePlayerFromLocationAsync(string locationId, string playerId)
|
|
{
|
|
var update = Builders<Location>.Update.Pull(l => l.Players, playerId);
|
|
await _locations.UpdateOneAsync(l => l.Id == locationId, update);
|
|
}
|
|
|
|
public virtual async Task AddItemToLocationAsync(string locationId, string itemId)
|
|
{
|
|
var update = Builders<Location>.Update.Push(l => l.Content, itemId);
|
|
await _locations.UpdateOneAsync(l => l.Id == locationId, update);
|
|
}
|
|
|
|
public virtual async Task RemoveItemFromLocationAsync(string locationId, string itemId)
|
|
{
|
|
var update = Builders<Location>.Update.Pull(l => l.Content, itemId);
|
|
await _locations.UpdateOneAsync(l => l.Id == locationId, update);
|
|
}
|
|
}
|