aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline.Tests/Helpers/HttpResponseExtensions.cs
blob: 2bd497f142570695adbb634eedde65d2f3c99e4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Timeline.Models.Converters;
using Timeline.Models.Http;

namespace Timeline.Tests.Helpers
{
    public static class HttpResponseExtensions
    {
        public static JsonSerializerOptions JsonSerializerOptions { get; }

        static HttpResponseExtensions()
        {
            JsonSerializerOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
            JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            JsonSerializerOptions.Converters.Add(new JsonDateTimeConverter());
        }

        public static async Task<T> ReadBodyAsJsonAsync<T>(this HttpResponseMessage response)
        {
            var stream = await response.Content.ReadAsStreamAsync();
            return await JsonSerializer.DeserializeAsync<T>(stream, JsonSerializerOptions);
        }

        public static Task<CommonResponse> ReadBodyAsCommonResponseAsync(this HttpResponseMessage response)
        {
            return response.ReadBodyAsJsonAsync<CommonResponse>();
        }
    }
}