56 lines
2.3 KiB
C#
56 lines
2.3 KiB
C#
using System.Reflection;
|
|||
|
|
using System.Runtime.CompilerServices;
|
||
|
|
using System.Text.Json;
|
||
|
|
using System.Text.Json.Serialization;
|
||
|
|
using System.Text.Json.Serialization.Metadata;
|
||
|
|
|
||
|
|
using PrivaPub.Api.Mastodon.Entities;
|
||
|
|
using PrivaPub.Api.Mastodon.Infrastructure;
|
||
|
|
using PrivaPub.ClientModels;
|
||
|
|
|
||
|
|
namespace PrivaPub.Infrastructure.Json
|
||
|
|
{
|
||
|
|
public static class PrivaPubJson
|
||
|
|
{
|
||
|
|
public static JsonSerializerOptions Web { get; } = Chained(new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||
|
|
|
||
|
|
public static JsonSerializerOptions Plain { get; } = Chained(new JsonSerializerOptions());
|
||
|
|
|
||
|
|
public static JsonSerializerOptions Chained(JsonSerializerOptions options)
|
||
|
|
{
|
||
|
|
Chain(options.TypeInfoResolverChain);
|
||
|
|
return options;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static void Chain(IList<IJsonTypeInfoResolver> chain)
|
||
|
|
{
|
||
|
|
var kept = chain.Where(r => r is not DefaultJsonTypeInfoResolver and not UnregisteredJson and not ClientModelsJsonContext and not ServerJsonContext).ToList();
|
||
|
|
chain.Clear();
|
||
|
|
chain.Add(ClientModelsJsonContext.Default);
|
||
|
|
chain.Add(ServerJsonContext.Default);
|
||
|
|
foreach (var resolver in kept)
|
||
|
|
chain.Add(resolver);
|
||
|
|
chain.Add(UnregisteredJson.Instance);
|
||
|
|
}
|
||
|
|
|
||
|
|
public static void Check(IHostEnvironment environment)
|
||
|
|
{
|
||
|
|
UnregisteredJson.Strict = !environment.IsProduction();
|
||
|
|
if (environment.IsProduction())
|
||
|
|
return;
|
||
|
|
var missing = Missing(ClientModelsJsonContext.Default, typeof(WebResult).Assembly, "PrivaPub.ClientModels")
|
||
|
|
.Concat(Missing(MastodonJsonContext.Default, typeof(Account).Assembly, "PrivaPub.Api.Mastodon.Entities"))
|
||
|
|
.ToList();
|
||
|
|
if (missing.Count > 0)
|
||
|
|
throw new InvalidOperationException("Not registered in a JsonSerializerContext (HR0306): " + string.Join(", ", missing));
|
||
|
|
}
|
||
|
|
|
||
|
|
static IEnumerable<string> Missing(IJsonTypeInfoResolver context, Assembly assembly, string space) =>
|
||
|
|
assembly.GetTypes()
|
||
|
|
.Where(t => t.IsClass && t.IsPublic && !t.IsAbstract && !t.IsGenericTypeDefinition && t.Namespace is { } ns && ns.StartsWith(space, StringComparison.Ordinal)
|
||
|
|
&& !ns.EndsWith(".Resources", StringComparison.Ordinal) && !typeof(Attribute).IsAssignableFrom(t) && !typeof(JsonSerializerContext).IsAssignableFrom(t)
|
||
|
|
&& t.GetCustomAttribute<CompilerGeneratedAttribute>() == null)
|
||
|
|
.Where(t => context.GetTypeInfo(t, new JsonSerializerOptions()) == null)
|
||
|
|
.Select(t => t.FullName);
|
||
|
|
}
|
||
|
|
}
|