Skip to content

Commit 6e8404e

Browse files
Refactor API response
1 parent 0db8d20 commit 6e8404e

File tree

11 files changed

+174
-271
lines changed

11 files changed

+174
-271
lines changed

SharpPusher/Models/Response.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// SharpPusher
2+
// Copyright (c) 2017 Coding Enthusiast
3+
// Distributed under the MIT software license, see the accompanying
4+
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.
5+
6+
namespace SharpPusher.Models
7+
{
8+
public class Response
9+
{
10+
public bool IsSuccess { get; private set; } = true;
11+
public string Message { get; private set; } = string.Empty;
12+
13+
private void SetMsg(string msg, bool success)
14+
{
15+
IsSuccess = success;
16+
Message = msg;
17+
}
18+
public void SetMessage(string msg) => SetMsg(msg, true);
19+
public void SetError(string msg) => SetMsg(msg, false);
20+
}
21+
}

SharpPusher/Models/State.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// SharpPusher
2+
// Copyright (c) 2017 Coding Enthusiast
3+
// Distributed under the MIT software license, see the accompanying
4+
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.
5+
6+
namespace SharpPusher.Models
7+
{
8+
public enum State
9+
{
10+
Ready,
11+
Broadcasting,
12+
Success,
13+
Failed
14+
}
15+
}

SharpPusher/Services/Api.cs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.
55

66
using Newtonsoft.Json.Linq;
7+
using SharpPusher.Models;
78
using System;
89
using System.Net.Http;
910
using System.Threading.Tasks;
@@ -23,7 +24,7 @@ public abstract class Api
2324
/// </summary>
2425
/// <param name="txHex">Signed raw transaction in hex format</param>
2526
/// <returns>Result of broadcasting.</returns>
26-
public abstract Task<Response<string>> PushTx(string txHex);
27+
public abstract Task<Response> PushTx(string txHex);
2728

2829

2930
/// <summary>
@@ -33,9 +34,9 @@ public abstract class Api
3334
/// <param name="jKey">The JSON key used for making the HttpContent in JSON format.</param>
3435
/// <param name="url">Api url to use.</param>
3536
/// <returns>Result of broadcasting.</returns>
36-
protected static async Task<Response<string>> PushTx(string txHex, string jKey, string url)
37+
protected static async Task<Response> PushTx(string txHex, string jKey, string url)
3738
{
38-
Response<string> resp = new();
39+
Response resp = new();
3940

4041
using HttpClient client = new();
4142
try
@@ -46,12 +47,16 @@ protected static async Task<Response<string>> PushTx(string txHex, string jKey,
4647
};
4748

4849
HttpResponseMessage httpResp = await client.PostAsync(url, new StringContent(tx.ToString()));
49-
resp.Result = await httpResp.Content.ReadAsStringAsync();
50+
if (!httpResp.IsSuccessStatusCode)
51+
{
52+
resp.SetError("API response doesn't indicate success.");
53+
}
54+
resp.SetMessage(await httpResp.Content.ReadAsStringAsync());
5055
}
5156
catch (Exception ex)
5257
{
5358
string errMsg = (ex.InnerException == null) ? ex.Message : ex.Message + " " + ex.InnerException;
54-
resp.Errors.Add(errMsg);
59+
resp.SetError(errMsg);
5560
}
5661

5762
return resp;

SharpPusher/Services/ErrorCollection.cs

Lines changed: 0 additions & 87 deletions
This file was deleted.

SharpPusher/Services/P2P.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using Autarkysoft.Bitcoin.Clients;
99
using Autarkysoft.Bitcoin.P2PNetwork.Messages;
1010
using Autarkysoft.Bitcoin.P2PNetwork.Messages.MessagePayloads;
11+
using SharpPusher.Models;
1112
using System.Threading.Tasks;
1213

1314
namespace SharpPusher.Services
@@ -46,25 +47,24 @@ public P2P(bool isMainNet)
4647

4748
public override string ApiName => "P2P";
4849

49-
public override async Task<Response<string>> PushTx(string txHex)
50+
public override async Task<Response> PushTx(string txHex)
5051
{
52+
Response resp = new();
53+
5154
Transaction tx = new(txHex);
5255
Message msg = new(new TxPayload(tx), netType);
5356

5457
MinimalClientSettings settings = new(netType, 4, null)
5558
{
5659
DnsSeeds = netType == NetworkType.MainNet ? DnsMain : DnsTest
5760
};
58-
MinimalClient client = new(settings);
61+
using MinimalClient client = new(settings);
5962
client.Start();
6063
await Task.Delay(TimeConstants.MilliSeconds.FiveSec);
6164
client.Send(msg);
6265

63-
return new Response<string>()
64-
{
65-
Result = $"Transaction was sent to {settings.MaxConnectionCount} nodes. " +
66-
$"Transaction ID: {tx.GetTransactionId()}"
67-
};
66+
resp.SetMessage($"Transaction was sent to {settings.MaxConnectionCount} nodes. Transaction ID: {tx.GetTransactionId()}");
67+
return resp;
6868
}
6969
}
7070
}

SharpPusher/Services/PushServices/BlockCypher.cs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,32 @@
44
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.
55

66
using Newtonsoft.Json.Linq;
7+
using SharpPusher.Models;
78
using System.Threading.Tasks;
89

910
namespace SharpPusher.Services.PushServices
1011
{
1112
public sealed class BlockCypher : Api
1213
{
13-
public override string ApiName
14-
{
15-
get { return "BlockCypher"; }
16-
}
14+
public override string ApiName => "BlockCypher";
1715

1816

19-
public override async Task<Response<string>> PushTx(string txHex)
17+
public override async Task<Response> PushTx(string txHex)
2018
{
21-
Response<string> resp = await PushTx(txHex, "tx", "https://api.blockcypher.com/v1/bcy/test/txs/push");
22-
if (resp.Errors.Any())
19+
Response resp = await PushTx(txHex, "tx", "https://api.blockcypher.com/v1/bcy/test/txs/push");
20+
if (!resp.IsSuccess)
2321
{
2422
return resp;
2523
}
2624

27-
JObject jResult = JObject.Parse(resp.Result);
25+
JObject jResult = JObject.Parse(resp.Message);
2826
if (jResult["error"] != null)
2927
{
30-
resp.Errors.Add(jResult["error"].ToString());
28+
resp.SetError(jResult["error"].ToString());
3129
}
3230
else
3331
{
34-
resp.Result = "Successfully done. Tx ID: " + jResult["hash"].ToString();
32+
resp.SetMessage($"Successfully done. Tx ID: {jResult["hash"]}");
3533
}
3634

3735
return resp;

SharpPusher/Services/PushServices/BlockchainInfo.cs

Lines changed: 28 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
using Newtonsoft.Json;
77
using Newtonsoft.Json.Linq;
8+
using SharpPusher.Models;
89
using System;
910
using System.Net.Http;
1011
using System.Text;
@@ -14,53 +15,48 @@ namespace SharpPusher.Services.PushServices
1415
{
1516
public sealed class BlockchainInfo : Api
1617
{
17-
public override string ApiName
18-
{
19-
get { return "Blockchain.Info"; }
20-
}
18+
public override string ApiName => "Blockchain.Info";
2119

22-
public async override Task<Response<string>> PushTx(string txHex)
20+
public async override Task<Response> PushTx(string txHex)
2321
{
24-
Response<string> resp = new Response<string>();
22+
using HttpClient client = new();
23+
Response resp = new();
2524

26-
using (HttpClient client = new HttpClient())
25+
try
2726
{
28-
try
29-
{
30-
client.BaseAddress = new Uri("https://blockchain.info");
27+
client.BaseAddress = new Uri("https://blockchain.info");
3128

32-
string json = JsonConvert.SerializeObject(txHex);
33-
string contentType = "application/x-www-form-urlencoded";
34-
HttpContent httpContent = new MultipartFormDataContent
35-
{
36-
new StringContent(json, Encoding.UTF8, contentType)
37-
};
29+
string json = JsonConvert.SerializeObject(txHex);
30+
string contentType = "application/x-www-form-urlencoded";
31+
HttpContent httpContent = new MultipartFormDataContent
32+
{
33+
new StringContent(json, Encoding.UTF8, contentType)
34+
};
3835

39-
HttpResponseMessage result = await client.PostAsync("pushtx", httpContent);
40-
string sResult = await result.Content.ReadAsStringAsync();
41-
if (result.IsSuccessStatusCode)
36+
HttpResponseMessage result = await client.PostAsync("pushtx", httpContent);
37+
string sResult = await result.Content.ReadAsStringAsync();
38+
if (result.IsSuccessStatusCode)
39+
{
40+
if (sResult != null && sResult.StartsWith("{\"error\":"))
4241
{
43-
if (sResult != null && sResult.StartsWith("{\"error\":"))
44-
{
45-
JObject jObject = JObject.Parse(sResult);
46-
resp.Errors.Add(jObject["error"].ToString());
47-
}
48-
else
49-
{
50-
resp.Result = sResult;
51-
}
42+
JObject jObject = JObject.Parse(sResult);
43+
resp.SetError(jObject["error"].ToString());
5244
}
5345
else
5446
{
55-
resp.Errors.Add(sResult);
47+
resp.SetMessage(sResult);
5648
}
5749
}
58-
catch (Exception ex)
50+
else
5951
{
60-
string errMsg = (ex.InnerException == null) ? ex.Message : ex.Message + " " + ex.InnerException;
61-
resp.Errors.Add(errMsg);
52+
resp.SetError(sResult);
6253
}
6354
}
55+
catch (Exception ex)
56+
{
57+
string errMsg = (ex.InnerException == null) ? ex.Message : ex.Message + " " + ex.InnerException;
58+
resp.SetError(errMsg);
59+
}
6460

6561
return resp;
6662
}

0 commit comments

Comments
 (0)