fix: dapper doesn't play nice with List<T>

This commit is contained in:
sam 2024-10-27 23:43:07 +01:00
parent 64b4c26d93
commit da4dfae27c
Signed by: sam
GPG key ID: 5F3C3C1B3166639D
4 changed files with 31 additions and 6 deletions

View file

@ -14,6 +14,9 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
using System.Data;
using System.Text.Json;
using System.Text.Json.Serialization;
using Catalogger.Backend.Database.Models;
using Dapper;
using NodaTime;
using Npgsql;
@ -113,6 +116,7 @@ public class DatabasePool
SqlMapper.AddTypeHandler(new UlongArrayHandler());
SqlMapper.AddTypeHandler(new PassthroughTypeHandler<Instant>());
SqlMapper.AddTypeHandler(new JsonTypeHandler<Guild.ChannelConfig>());
}
// Copied from PluralKit:
@ -144,6 +148,21 @@ public class DatabasePool
public override ulong[] Parse(object value) =>
Array.ConvertAll((long[])value, i => (ulong)i);
}
public class JsonTypeHandler<T> : SqlMapper.TypeHandler<T>
{
public override T Parse(object value)
{
string json = (string)value;
return JsonSerializer.Deserialize<T>(json)
?? throw new CataloggerError("JsonTypeHandler<T> returned null");
}
public override void SetValue(IDbDataParameter parameter, T? value)
{
parameter.Value = JsonSerializer.Serialize(value);
}
}
}
public static class ServiceCollectionDatabaseExtensions