using System;
using System.Threading.Tasks;
using Swan.Formatters;
using Swan.Logging;
namespace EmbedIO
{
///
/// Provides standard request deserialization callbacks.
///
public static class RequestDeserializer
{
///
/// The default request deserializer used by EmbedIO.
/// Equivalent to .
///
/// The expected type of the deserialized data.
/// The whose request body is to be deserialized.
/// A Task, representing the ongoing operation,
/// whose result will be the deserialized data.
public static Task Default(IHttpContext context) => Json(context);
///
/// Asynchronously deserializes a request body in JSON format.
///
/// The expected type of the deserialized data.
/// The whose request body is to be deserialized.
/// A Task, representing the ongoing operation,
/// whose result will be the deserialized data.
public static Task Json(IHttpContext context) => JsonInternal(context, default);
///
/// Returns a RequestDeserializerCallback
/// that will deserialize an HTTP request body in JSON format, using the specified property name casing.
///
/// The expected type of the deserialized data.
/// The to use.
/// A that can be used to deserialize
/// a JSON request body.
public static RequestDeserializerCallback Json(JsonSerializerCase jsonSerializerCase)
=> context => JsonInternal(context, jsonSerializerCase);
private static async Task JsonInternal(IHttpContext context, JsonSerializerCase jsonSerializerCase)
{
string body;
using (var reader = context.OpenRequestText())
{
body = await reader.ReadToEndAsync().ConfigureAwait(false);
}
try
{
return Swan.Formatters.Json.Deserialize(body, jsonSerializerCase);
}
catch (FormatException)
{
$"[{context.Id}] Cannot convert JSON request body to {typeof(TData).Name}, sending 400 Bad Request..."
.Warn($"{nameof(RequestDeserializer)}.{nameof(Json)}");
throw HttpException.BadRequest("Incorrect request data format.");
}
}
}
}