bibblan/Server/Business/Services/DatabaseService.cs
2025-09-09 17:41:55 +02:00

56 lines
1.9 KiB
C#

using Bibblan.Models;
using Bibblan.ViewModels;
using Dapper;
using Microsoft.Extensions.Options;
using Npgsql;
namespace Bibblan.Business.Services
{
public class BookFilter
{
public int? Author;
public string? Query;
}
public class DatabaseService
{
BibblanOptions settings;
public DatabaseService(IOptions<BibblanOptions> options) {
settings = options.Value;
}
public IEnumerable<Books> GetBooks(int count, BookFilter filter = null)
{
var conn = new NpgsqlConnection(settings.BibblanConnection);
var query = "select * from books";
if(filter != null)
{
query += " where ";
if(filter.Author != null)
{
query += $"id in (select book from books_authors_link where author = {filter.Author})";
} else if(!String.IsNullOrWhiteSpace(query))
{
filter.Query = filter.Query.ToLowerInvariant();
query += $"lower(title) like '%{filter.Query}%' or lower(author_sort) like '%{filter.Query}%'";
}
}
return conn.Query<Books>(query).Take(count).ToList();
}
public IEnumerable<AuthorVm> GetAuthors(int count, BookFilter filter = null)
{
var query = "select a.id, a.name, count(bal.*) as bookcount\r\nfrom authors a\r\nleft join books_authors_link bal on a.id = bal.author\r\ngroup by a.id , a.name ";
if(!String.IsNullOrWhiteSpace(filter?.Query))
{
filter.Query = filter.Query.ToLowerInvariant();
query += $" having lower(a.name) like '%{filter.Query}%'";
}
var conn = new NpgsqlConnection(settings.BibblanConnection);
return conn.Query<AuthorVm>(query).Take(count).ToList();
}
}
}