2012-08-15 13:20:29 +00:00
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using MediaBrowser.Common.Serialization;
|
|
|
|
|
|
2012-07-21 18:39:47 +00:00
|
|
|
|
namespace MediaBrowser.Common.Net.Handlers
|
2012-07-20 02:22:44 +00:00
|
|
|
|
{
|
2012-08-17 13:16:50 +00:00
|
|
|
|
public abstract class BaseJsonHandler<T> : BaseHandler
|
2012-07-20 02:22:44 +00:00
|
|
|
|
{
|
2012-08-19 20:38:31 +00:00
|
|
|
|
public override Task<string> GetContentType()
|
2012-07-20 02:22:44 +00:00
|
|
|
|
{
|
2012-08-19 20:38:31 +00:00
|
|
|
|
return Task.Run(() =>
|
|
|
|
|
{
|
|
|
|
|
return MimeTypes.JsonMimeType;
|
|
|
|
|
});
|
2012-08-15 13:20:29 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private bool _ObjectToSerializeEnsured = false;
|
2012-08-17 13:16:50 +00:00
|
|
|
|
private T _ObjectToSerialize;
|
2012-08-15 13:20:29 +00:00
|
|
|
|
|
2012-08-19 20:38:31 +00:00
|
|
|
|
private async Task EnsureObjectToSerialize()
|
2012-08-15 13:20:29 +00:00
|
|
|
|
{
|
|
|
|
|
if (!_ObjectToSerializeEnsured)
|
|
|
|
|
{
|
2012-08-19 20:38:31 +00:00
|
|
|
|
_ObjectToSerialize = await GetObjectToSerialize();
|
2012-08-15 13:20:29 +00:00
|
|
|
|
|
|
|
|
|
if (_ObjectToSerialize == null)
|
|
|
|
|
{
|
|
|
|
|
StatusCode = 404;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_ObjectToSerializeEnsured = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2012-08-19 20:38:31 +00:00
|
|
|
|
protected abstract Task<T> GetObjectToSerialize();
|
2012-08-15 13:20:29 +00:00
|
|
|
|
|
2012-08-19 20:38:31 +00:00
|
|
|
|
protected override async Task PrepareResponse()
|
2012-08-15 13:20:29 +00:00
|
|
|
|
{
|
2012-08-19 20:38:31 +00:00
|
|
|
|
await EnsureObjectToSerialize();
|
2012-08-15 13:20:29 +00:00
|
|
|
|
}
|
|
|
|
|
|
2012-08-19 20:38:31 +00:00
|
|
|
|
protected async override Task WriteResponseToOutputStream(Stream stream)
|
2012-08-15 13:20:29 +00:00
|
|
|
|
{
|
2012-08-19 20:38:31 +00:00
|
|
|
|
await EnsureObjectToSerialize();
|
|
|
|
|
|
|
|
|
|
JsonSerializer.SerializeToStream<T>(_ObjectToSerialize, stream);
|
2012-07-20 02:22:44 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|