mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
Initial KV API concept
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
#nullable enable
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Kruzya.TelegramBot.Core.Data;
|
||||
using Kruzya.TelegramBot.Core.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Kruzya.TelegramBot.Core.Option;
|
||||
|
||||
public class CoreContextStorageService : IOptionStorageAdapter
|
||||
{
|
||||
private CoreContext _db;
|
||||
public CoreContextStorageService(CoreContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task<byte[]?> LoadValueAsync(IOptionKey key)
|
||||
{
|
||||
var entity = await BuildQueryForKey(key).FirstOrDefaultAsync();
|
||||
|
||||
return entity?.Value;
|
||||
}
|
||||
|
||||
public async Task SaveValueAsync(IOptionKey key, byte[] value)
|
||||
{
|
||||
var entity = await BuildQueryForKey(key).FirstOrDefaultAsync();
|
||||
if (entity == null)
|
||||
{
|
||||
entity = await CreateEntity(key);
|
||||
}
|
||||
|
||||
entity.Value = value;
|
||||
_db.AddOrUpdate(entity);
|
||||
}
|
||||
|
||||
private IQueryable<BotUserValue> BuildQueryForKey(IOptionKey key)
|
||||
{
|
||||
var legacyUserId = key.UserId ?? 0;
|
||||
|
||||
return _db.UserValues.Where(e => e.BotUser.ChatId == key.ChatId && e.BotUser.UserId == legacyUserId
|
||||
&& e.Name == key.Identifier);
|
||||
}
|
||||
|
||||
private async Task<BotUserValue> CreateEntity(IOptionKey key)
|
||||
{
|
||||
var entity = _db.UserValues.Create()!;
|
||||
entity.BotUser = await _db.Users.FindOrCreate(key.ChatId, key.UserId ?? 0);
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user