store DateTimeOffset values in date fields instead of the default array (#651)

This commit is contained in:
Jesse Plamondon-Willard 2019-07-24 18:31:24 -04:00
parent e856d5efeb
commit f6b336def7
No known key found for this signature in database
GPG Key ID: CF8B1456B3E29F49
2 changed files with 47 additions and 1 deletions

View File

@ -0,0 +1,40 @@
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
namespace StardewModdingAPI.Web.Framework.Caching
{
/// <summary>Serialises <see cref="DateTimeOffset"/> to a UTC date field instead of the default array.</summary>
public class UtcDateTimeOffsetSerializer : StructSerializerBase<DateTimeOffset>
{
/*********
** Fields
*********/
/// <summary>The underlying date serializer.</summary>
private static readonly DateTimeSerializer DateTimeSerializer = new DateTimeSerializer(DateTimeKind.Utc, BsonType.DateTime);
/*********
** Public methods
*********/
/// <summary>Deserializes a value.</summary>
/// <param name="context">The deserialization context.</param>
/// <param name="args">The deserialization args.</param>
/// <returns>A deserialized value.</returns>
public override DateTimeOffset Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
DateTime date = UtcDateTimeOffsetSerializer.DateTimeSerializer.Deserialize(context, args);
return new DateTimeOffset(date, TimeSpan.Zero);
}
/// <summary>Serializes a value.</summary>
/// <param name="context">The serialization context.</param>
/// <param name="args">The serialization args.</param>
/// <param name="value">The object.</param>
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTimeOffset value)
{
UtcDateTimeOffsetSerializer.DateTimeSerializer.Serialize(context, args, value.UtcDateTime);
}
}
}

View File

@ -7,10 +7,12 @@ using Microsoft.AspNetCore.Rewrite;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using Newtonsoft.Json;
using StardewModdingAPI.Toolkit.Serialisation;
using StardewModdingAPI.Web.Framework;
using StardewModdingAPI.Web.Framework.Caching;
using StardewModdingAPI.Web.Framework.Caching.Wiki;
using StardewModdingAPI.Web.Framework.Clients.Chucklefish;
using StardewModdingAPI.Web.Framework.Clients.GitHub;
@ -81,7 +83,11 @@ namespace StardewModdingAPI.Web
}
// init MongoDB
services.AddSingleton<IMongoDatabase>(serv => new MongoClient(mongoConfig.GetConnectionString()).GetDatabase(mongoConfig.Database));
services.AddSingleton<IMongoDatabase>(serv =>
{
BsonSerializer.RegisterSerializer(new UtcDateTimeOffsetSerializer());
return new MongoClient(mongoConfig.GetConnectionString()).GetDatabase(mongoConfig.Database);
});
services.AddSingleton<IWikiCacheRepository>(serv => new WikiCacheRepository(serv.GetRequiredService<IMongoDatabase>()));
// init Hangfire