-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathResponseBuilder.cs
45 lines (39 loc) · 1.76 KB
/
ResponseBuilder.cs
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
36
37
38
39
40
41
42
43
44
45
using System;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Dwolla.Client.Models.Responses;
using Newtonsoft.Json;
namespace Dwolla.Client.Rest
{
public interface IResponseBuilder
{
Task<RestResponse<T>> Build<T>(HttpResponseMessage response);
RestResponse<T> Error<T>(HttpResponseMessage response, string code, string message, string rawContent = null);
}
public class ResponseBuilder : IResponseBuilder
{
public async Task<RestResponse<T>> Build<T>(HttpResponseMessage response)
{
using (var content = response.Content)
{
if (content == null) return Error<T>(response, "NullResponse", "Response content is null", null);
var rawContent = await content.ReadAsStringAsync();
try
{
return (int)response.StatusCode >= 400
? Error<T>(response, JsonConvert.DeserializeObject<ErrorResponse>(rawContent), rawContent)
: new RestResponse<T>(response, JsonConvert.DeserializeObject<T>(rawContent), rawContent);
}
catch (Exception e)
{
return Error<T>(response, "DeserializationException", e.Message, rawContent);
}
}
}
public RestResponse<T> Error<T>(HttpResponseMessage response, string code, string message, string rawContent) =>
Error<T>(response, new ErrorResponse { Code = code, Message = message }, rawContent);
private static RestResponse<T> Error<T>(HttpResponseMessage response, ErrorResponse error, string rawContent) =>
new RestResponse<T>(response, default(T), rawContent, error);
}
}