93 lines
3.3 KiB
C#
93 lines
3.3 KiB
C#
using System.Text.Json;
|
|
using Dapper;
|
|
using ScrapperAPI.Dtos;
|
|
using ScrapperAPI.Interfaces;
|
|
|
|
namespace ScrapperAPI.Repositories;
|
|
|
|
public sealed class ExtractionModelRepository : IExtractionModelRepository
|
|
{
|
|
private readonly IDbConnectionFactory _db;
|
|
|
|
public ExtractionModelRepository(IDbConnectionFactory db) => _db = db;
|
|
|
|
public async Task<long> CreateAsync(CreateExtractionModelDto dto, CancellationToken ct)
|
|
{
|
|
const string sql = """
|
|
insert into extraction_model(name, version, description, definition)
|
|
values (@name, @version, @description, @definition::jsonb)
|
|
returning id;
|
|
""";
|
|
|
|
using var conn = await _db.CreateOpenConnectionAsync(ct);
|
|
return await conn.ExecuteScalarAsync<long>(new CommandDefinition(sql, new
|
|
{
|
|
name = dto.Name,
|
|
version = dto.Version,
|
|
description = dto.Description,
|
|
definition = dto.Definition.RootElement.GetRawText()
|
|
}, cancellationToken: ct));
|
|
}
|
|
|
|
public async Task<IReadOnlyList<ExtractionModelRow>> GetAllAsync(CancellationToken ct)
|
|
{
|
|
const string sql = """
|
|
select
|
|
id,
|
|
name,
|
|
version,
|
|
description,
|
|
definition::text as definition_json,
|
|
created_at,
|
|
updated_at
|
|
from extraction_model
|
|
order by name, version, id;
|
|
""";
|
|
|
|
using var conn = await _db.CreateOpenConnectionAsync(ct);
|
|
var rows = await conn.QueryAsync<ModelRaw>(new CommandDefinition(sql, cancellationToken: ct));
|
|
return rows.Select(r => r.ToDto()).ToList();
|
|
}
|
|
|
|
public async Task<ExtractionModelRow?> GetByIdAsync(long id, CancellationToken ct)
|
|
{
|
|
const string sql = """
|
|
select
|
|
id as Id,
|
|
name as Name,
|
|
version as Version,
|
|
description as Description,
|
|
definition as DefinitionJson,
|
|
created_at as CreatedAt,
|
|
updated_at as UpdatedAt
|
|
from extraction_model
|
|
where id = @id
|
|
""";
|
|
|
|
using var conn = await _db.CreateOpenConnectionAsync(ct);
|
|
var row = await conn.QuerySingleOrDefaultAsync<ModelRaw>(new CommandDefinition(sql, new { id }, cancellationToken: ct));
|
|
return row?.ToDto();
|
|
}
|
|
|
|
private class ModelRaw
|
|
{
|
|
public long Id { get; set; }
|
|
public string Name { get; set; } = default!;
|
|
public int Version { get; set; }
|
|
public string? Description { get; set; }
|
|
public string DefinitionJson { get; set; } = default!;
|
|
public DateTime CreatedAt { get; set; }
|
|
public DateTime UpdatedAt { get; set; }
|
|
|
|
public ExtractionModelRow ToDto() => new(
|
|
Id,
|
|
Name,
|
|
Version,
|
|
Description,
|
|
JsonDocument.Parse(DefinitionJson),
|
|
CreatedAt,
|
|
UpdatedAt
|
|
);
|
|
}
|
|
}
|