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-22 02:50:59 +00:00
|
|
|
|
return Task.FromResult<string>(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-22 02:50:59 +00:00
|
|
|
|
_ObjectToSerialize = await GetObjectToSerialize().ConfigureAwait(false);
|
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-22 02:50:59 +00:00
|
|
|
|
protected override Task PrepareResponse()
|
2012-08-15 13:20:29 +00:00
|
|
|
|
{
|
2012-08-22 02:50:59 +00:00
|
|
|
|
return 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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|