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

97 lines
2.8 KiB
C#
Raw Normal View History

using System.Data;
using Dapper;
using Microsoft.Extensions.Configuration;
using Newsbot.Collector.Domain.Models;
using Npgsql;
namespace Newsbot.Collector.Database.Repositories;
public class SubscriptionsTable
{
private string _connectionString;
public SubscriptionsTable(string connectionString)
{
_connectionString = connectionString;
}
public SubscriptionsTable(IConfiguration configuration)
{
var connstr = configuration.GetConnectionString("database");
if (connstr is null)
{
connstr = "";
}
_connectionString = connstr;
}
private IDbConnection OpenConnection(string connectionString)
{
var conn = new NpgsqlConnection(_connectionString);
conn.Open();
return conn;
}
public void New(SubscriptionModel model)
{
using var conn = OpenConnection(_connectionString);
var query = "Insert Into subscriptions (ID, DiscordWebHookId, SourceId) Values (@id, @webhookid, @sourceid);";
conn.Execute(query, new
{
id = Guid.NewGuid(),
webhookid = model.DiscordWebHookID,
sourceid = model.SourceID
});
}
public List<SubscriptionModel> List(int limit = 25)
{
using var conn = OpenConnection(_connectionString);
var query = "Select * From subscriptions Limit @limit;";
return conn.Query<SubscriptionModel>(query, new
{
limit = limit,
}).ToList();
}
// todo add paging
public List<SubscriptionModel> ListBySourceID(Guid sourceID)
{
using var conn = OpenConnection(_connectionString);
var query = "Select * From subscriptions where sourceid = @sourceid";
return conn.Query<SubscriptionModel>(query, new
{
sourceid = sourceID
}).ToList();
}
public List<SubscriptionModel> GetByWebhookAndSource(Guid webhookId, Guid sourceId)
{
using var conn = OpenConnection(_connectionString);
var query = "Select * From subscriptions Where discordwebhookid = @webhookid and sourceid = @sourceid;";
return conn.Query<SubscriptionModel>(query, new
{
webhookid = webhookId,
sourceid = sourceId,
}).ToList();
}
public List<SubscriptionModel> ListByWebhook(Guid webhookId)
{
using var conn = OpenConnection(_connectionString);
var query = "Select * From subscriptions Where discordwebhookid = @webhookid";
return conn.Query<SubscriptionModel>(query, new
{
webhookid = webhookId,
}).ToList();
}
public void Delete(Guid id)
{
using var conn = OpenConnection(_connectionString);
var query = "Delete From subscriptions Where id = @id;";
conn.Execute(query, new {
id = id
});
}
}