Newsbot.Collector/Newsbot.Collector.Database/Repositories/SubscriptionsTable.cs

93 lines
2.9 KiB
C#

using System.Data;
using Dapper;
using Microsoft.Extensions.Configuration;
using Newsbot.Collector.Domain.Entities;
using Newsbot.Collector.Domain.Interfaces;
using Newsbot.Collector.Domain.Models;
using Npgsql;
namespace Newsbot.Collector.Database.Repositories;
public class SubscriptionsTable : ISubscriptionRepository
{
private readonly string _connectionString;
public SubscriptionsTable(string connectionString)
{
_connectionString = connectionString;
}
public SubscriptionsTable(IConfiguration configuration)
{
var connstr = configuration.GetConnectionString("database");
if (connstr is null) connstr = "";
_connectionString = connstr;
}
public SubscriptionEntity New(SubscriptionEntity model)
{
model.Id = new Guid();
using var context = new DatabaseContext(_connectionString);
context.Subscriptions.Add(model);
context.SaveChanges();
return model;
}
public List<SubscriptionEntity> List(int page = 0, int count = 25)
{
using var context = new DatabaseContext(_connectionString);
return context.Subscriptions.Skip(page * count).Take(count).ToList();
}
public List<SubscriptionEntity> ListBySourceId(Guid id, int page = 0, int count = 25)
{
using var context = new DatabaseContext(_connectionString);
return context.Subscriptions.Where(f => f.SourceId.Equals(id))
.Skip(page * count)
.ToList();
}
public List<SubscriptionEntity> ListByWebhook(Guid id, int page = 0, int count = 25)
{
using var context = new DatabaseContext(_connectionString);
return context.Subscriptions.Where(f => f.DiscordWebHookId.Equals(id)).Skip(page * count).ToList();
}
public SubscriptionEntity GetById(Guid id)
{
using var context = new DatabaseContext(_connectionString);
var res = context.Subscriptions
.FirstOrDefault(f => f.Id.Equals(id));
return res ??= new SubscriptionEntity();
}
public SubscriptionEntity GetByWebhookAndSource(Guid webhookId, Guid sourceId)
{
using var context = new DatabaseContext(_connectionString);
var res = context.Subscriptions
.Where(f => f.DiscordWebHookId.Equals(webhookId))
.FirstOrDefault(f => f.SourceId.Equals(sourceId));
return res ??= new SubscriptionEntity();
}
public void Delete(Guid id)
{
using var context = new DatabaseContext(_connectionString);
var res = context.Subscriptions.FirstOrDefault(f => f.Id.Equals(id));
if (res is null)
{
return;
}
context.Subscriptions.Remove(res);
context.SaveChanges();
}
private IDbConnection OpenConnection(string connectionString)
{
var conn = new NpgsqlConnection(_connectionString);
conn.Open();
return conn;
}
}