-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathItemService.cs
89 lines (77 loc) · 3 KB
/
ItemService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Wfdf.Core.Models;
namespace Wfdf.Core.Service;
public class ItemService
{
private readonly ILogger<ItemService> _logger;
private readonly IMongoCollection<Item> _items;
public ItemService(WfdfDatabase database, ILogger<ItemService> logger)
{
_logger = logger;
_items = database.GetCollection<Item>("items");
try
{
_items.Indexes.CreateOne(
new CreateIndexModel<Item>(
Builders<Item>.IndexKeys.Ascending(item => item.uniqueName),
new CreateIndexOptions { Unique = true }
)
);
_items.Indexes.CreateOne(
new CreateIndexModel<Item>(
Builders<Item>.IndexKeys.Text(item => item.name),
new CreateIndexOptions { Unique = false }
)
);
}
catch (MongoCommandException ex)
{
_logger.LogError(ex, "Failed to create index");
}
}
private ReplaceOneModel<Item> CreateItemUpsertModel(Item item)
{
return new ReplaceOneModel<Item>(
Builders<Item>.Filter.Eq(s => s.uniqueName, item.uniqueName),
item
)
{ IsUpsert = true };
}
public async Task<BulkWriteResult> UpsertItemsAsync(List<Item> items)
{
var updates = new List<WriteModel<Item>>();
foreach (var item in items)
{
updates.Add(CreateItemUpsertModel(item));
}
return await _items.BulkWriteAsync(updates);
}
public async Task<IEnumerable<PartialItem>> SearchForItemAsync(string name)
{
var filter = Builders<Item>.Filter.Regex("name", new BsonRegularExpression(name, "i"));
var matches = await _items.Find(filter).As<PartialItem>().ToListAsync();
return matches;
}
public async Task<Item> GetItemAsync(string uniqueName)
=> await _items.Find(i => i.uniqueName == uniqueName).FirstOrDefaultAsync();
public async Task<IEnumerable<PartialItem>> GetRandomItemsAsync(int count)
{
var categoryBlacklist = new List<string> { "Mods", "Arcanes", "Relics" };
var items = await _items.AsQueryable()
.Where(i => !categoryBlacklist.Contains(i.category))
.Sample(count)
.Select(i => (PartialItem)i)
.ToListAsync();
return items;
}
public async Task<IEnumerable<Item>> FindItemsWithComponentAsync(string componentUniqueName)
=> await _items.Find(Builders<Item>.Filter.ElemMatch(i => i.components, c => c.uniqueName.Equals(componentUniqueName)))
.ToListAsync();
public async Task<IEnumerable<PartialItem>> FindItemsWithDropSourceAsync(string location)
=> await _items.Find(Builders<Item>.Filter.ElemMatch(i => i.drops, d => d.location.Equals(location)))
.As<PartialItem>()
.ToListAsync();
}