58 lines
1.5 KiB
C#
58 lines
1.5 KiB
C#
using System.Collections.Generic;
|
|
using System.Threading.Tasks;
|
|
using GameAuthApi.Models;
|
|
using Microsoft.Extensions.Configuration;
|
|
using MongoDB.Driver;
|
|
|
|
namespace GameAuthApi.Services;
|
|
|
|
public class ItemService
|
|
{
|
|
private readonly IMongoCollection<Item> _items;
|
|
|
|
public ItemService(IConfiguration config)
|
|
{
|
|
var client = new MongoClient(config["MongoDB:ConnectionString"]);
|
|
var db = client.GetDatabase(config["MongoDB:DatabaseName"]);
|
|
_items = db.GetCollection<Item>("Items");
|
|
}
|
|
|
|
public virtual async Task CreateAsync(Item item)
|
|
{
|
|
await _items.InsertOneAsync(item);
|
|
}
|
|
|
|
public virtual async Task<List<Item>> GetByLocationAsync(string locationId)
|
|
{
|
|
return await _items.Find(i => i.LocationId == locationId).ToListAsync();
|
|
}
|
|
|
|
public virtual async Task<Item> GetByIdAsync(string id)
|
|
{
|
|
if (!MongoDB.Bson.ObjectId.TryParse(id, out _))
|
|
return null;
|
|
|
|
return await _items.Find(i => i.Id == id).FirstOrDefaultAsync();
|
|
}
|
|
|
|
public virtual async Task UpdateAsync(Item item)
|
|
{
|
|
await _items.ReplaceOneAsync(i => i.Id == item.Id, item);
|
|
}
|
|
|
|
public virtual async Task DeleteAsync(string id)
|
|
{
|
|
await _items.DeleteOneAsync(i => i.Id == id);
|
|
}
|
|
|
|
public virtual async Task DeleteByLocationAsync(string locationId)
|
|
{
|
|
await _items.DeleteManyAsync(i => i.LocationId == locationId);
|
|
}
|
|
|
|
public virtual async Task DeleteAllAsync()
|
|
{
|
|
await _items.DeleteManyAsync(_ => true);
|
|
}
|
|
}
|