Skip to content

Commit d3e3685

Browse files
committed
Code review - Refactor
1 parent 62ed77b commit d3e3685

File tree

5 files changed

+149
-118
lines changed

5 files changed

+149
-118
lines changed

demo/Assets/MainScript.cs

+19-12
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@ public class MainScript : MonoBehaviour {
88

99
private readonly string basePath = "https://jsonplaceholder.typicode.com";
1010

11+
private void LogMessage(string title, string message) {
12+
#if UNITY_EDITOR
13+
EditorUtility.DisplayDialog (title, message, "Ok");
14+
#else
15+
Debug.Log(message);
16+
#endif
17+
}
18+
1119
public void Get(){
1220

1321
// We can add default request headers for all requests
@@ -16,14 +24,13 @@ public void Get(){
1624
RequestHelper requestOptions = null;
1725

1826
RestClient.GetArray<Post>(basePath + "/posts").Then(res => {
19-
EditorUtility.DisplayDialog ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true), "Ok");
27+
this.LogMessage ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true));
2028
return RestClient.GetArray<Todo>(basePath + "/todos");
2129
}).Then(res => {
22-
EditorUtility.DisplayDialog ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true), "Ok");
30+
this.LogMessage ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true));
2331
return RestClient.GetArray<User>(basePath + "/users");
2432
}).Then(res => {
25-
EditorUtility.DisplayDialog ("Users", JsonHelper.ArrayToJsonString<User>(res, true), "Ok");
26-
33+
this.LogMessage ("Users", JsonHelper.ArrayToJsonString<User>(res, true));
2734

2835
// We can add specific options and override default headers for a request
2936
requestOptions = new RequestHelper {
@@ -35,12 +42,12 @@ public void Get(){
3542
};
3643
return RestClient.GetArray<Photo>(requestOptions);
3744
}).Then(res => {
38-
EditorUtility.DisplayDialog("Header", requestOptions.GetHeader("Authorization"), "Ok");
45+
this.LogMessage("Header", requestOptions.GetHeader("Authorization"));
3946

4047
// And later we can clean the default headers for all requests
4148
RestClient.CleanDefaultHeaders();
4249

43-
}).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok"));
50+
}).Catch(err => this.LogMessage ("Error", err.Message));
4451
}
4552

4653
public void Post(){
@@ -50,8 +57,8 @@ public void Post(){
5057
body = "My first message",
5158
userId = 26
5259
})
53-
.Then(res => EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(res, true), "Ok"))
54-
.Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok"));
60+
.Then(res => this.LogMessage ("Success", JsonUtility.ToJson(res, true)))
61+
.Catch(err => this.LogMessage ("Error", err.Message));
5562
}
5663

5764
public void Put(){
@@ -70,10 +77,10 @@ public void Put(){
7077
}
7178
}, (err, res, body) => {
7279
if(err != null){
73-
EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
80+
this.LogMessage ("Error", err.Message);
7481
}
7582
else{
76-
EditorUtility.DisplayDialog ("Success", res.Text, "Ok");
83+
this.LogMessage ("Success", res.Text);
7784
}
7885
});
7986
}
@@ -82,10 +89,10 @@ public void Delete(){
8289

8390
RestClient.Delete(basePath + "/posts/1", (err, res) => {
8491
if(err != null){
85-
EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
92+
this.LogMessage ("Error", err.Message);
8693
}
8794
else{
88-
EditorUtility.DisplayDialog ("Success", "Status: " + res.StatusCode.ToString(), "Ok");
95+
this.LogMessage ("Success", "Status: " + res.StatusCode.ToString());
8996
}
9097
});
9198
}

src/Proyecto26.RestClient/Proyecto26.RestClient.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@
6969
<Compile Include="Utils\StaticCoroutine.cs" />
7070
<Compile Include="RestClient.cs" />
7171
<Compile Include="RestClientPromise.cs" />
72+
<Compile Include="Utils\Common.cs" />
7273
</ItemGroup>
7374
<ItemGroup>
7475
<None Include="packages.config" />
+122
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
using System.Text;
2+
using System.Collections;
3+
using UnityEngine;
4+
using UnityEngine.Networking;
5+
6+
namespace Proyecto26.Common
7+
{
8+
public static class Common
9+
{
10+
private const string CONTENT_TYPE_HEADER = "Content-Type";
11+
private const string CONTENT_TYPE_JSON = "application/json";
12+
13+
private static string GetFormSectionsContentType(out byte[] bodyRaw, RequestHelper options)
14+
{
15+
byte[] boundary = UnityWebRequest.GenerateBoundary();
16+
byte[] formSections = UnityWebRequest.SerializeFormSections(options.FormSections, boundary);
17+
byte[] terminate = Encoding.UTF8.GetBytes(string.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--"));
18+
bodyRaw = new byte[formSections.Length + terminate.Length];
19+
System.Buffer.BlockCopy(formSections, 0, bodyRaw, 0, formSections.Length);
20+
System.Buffer.BlockCopy(terminate, 0, bodyRaw, formSections.Length, terminate.Length);
21+
return string.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary));
22+
}
23+
24+
private static void ConfigureWebRequestWithOptions(UnityWebRequest request, byte[] bodyRaw, string contentType, RequestHelper options)
25+
{
26+
#if UNITY_2018_1_OR_NEWER
27+
if (options.CertificateHandler is CertificateHandler)
28+
request.certificateHandler = options.CertificateHandler;
29+
#endif
30+
if (options.UploadHandler is UploadHandler)
31+
request.uploadHandler = options.UploadHandler;
32+
if (bodyRaw != null)
33+
{
34+
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
35+
request.uploadHandler.contentType = contentType;
36+
}
37+
if (options.DownloadHandler is DownloadHandler)
38+
request.downloadHandler = options.DownloadHandler;
39+
else
40+
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
41+
if (!string.IsNullOrEmpty(contentType))
42+
{
43+
request.SetRequestHeader(CONTENT_TYPE_HEADER, contentType);
44+
}
45+
foreach (var header in RestClient.DefaultRequestHeaders)
46+
{
47+
request.SetRequestHeader(header.Key, header.Value);
48+
}
49+
foreach (var header in options.Headers)
50+
{
51+
request.SetRequestHeader(header.Key, header.Value);
52+
}
53+
if (options.Timeout.HasValue)
54+
{
55+
request.timeout = options.Timeout.Value;
56+
}
57+
if (options.ChunkedTransfer.HasValue)
58+
{
59+
request.chunkedTransfer = options.ChunkedTransfer.Value;
60+
}
61+
if (options.UseHttpContinue.HasValue)
62+
{
63+
request.useHttpContinue = options.UseHttpContinue.Value;
64+
}
65+
if (options.RedirectLimit.HasValue)
66+
{
67+
request.redirectLimit = options.RedirectLimit.Value;
68+
}
69+
options.Request = request;
70+
}
71+
72+
/// <summary>
73+
/// Send the web request to the server
74+
/// </summary>
75+
/// <returns>An UnityWebRequestAsyncOperation object.</returns>
76+
/// <param name="request">An UnityWebRequest object.</param>
77+
/// <param name="options">An options object.</param>
78+
public static IEnumerator SendWebRequestWithOptions(this UnityWebRequest request, RequestHelper options)
79+
{
80+
byte[] bodyRaw = options.BodyRaw;
81+
string contentType = string.Empty;
82+
if (!options.Headers.TryGetValue(CONTENT_TYPE_HEADER, out contentType))
83+
{
84+
contentType = CONTENT_TYPE_JSON;
85+
}
86+
if (options.Body != null || !string.IsNullOrEmpty(options.BodyString))
87+
{
88+
var bodyString = options.BodyString;
89+
if (options.Body != null)
90+
{
91+
bodyString = JsonUtility.ToJson(options.Body);
92+
}
93+
bodyRaw = Encoding.UTF8.GetBytes(bodyString.ToCharArray());
94+
}
95+
else if (options.SimpleForm != null && options.SimpleForm.Count > 0)
96+
{
97+
bodyRaw = UnityWebRequest.SerializeSimpleForm(options.SimpleForm);
98+
contentType = "application/x-www-form-urlencoded";
99+
}
100+
else if (options.FormSections != null && options.FormSections.Count > 0)
101+
{
102+
contentType = GetFormSectionsContentType(out bodyRaw, options);
103+
}
104+
else if (options.FormData is WWWForm)
105+
{
106+
//The Content-Type header will be copied from the formData parameter
107+
contentType = string.Empty;
108+
}
109+
if (!string.IsNullOrEmpty(options.ContentType))
110+
{
111+
contentType = options.ContentType;
112+
}
113+
114+
ConfigureWebRequestWithOptions(request, bodyRaw, contentType, options);
115+
#if UNITY_2017_2_OR_NEWER
116+
yield return request.SendWebRequest();
117+
#else
118+
yield return request.Send();
119+
#endif
120+
}
121+
}
122+
}

src/Proyecto26.RestClient/Utils/Extensions.cs

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1-
using UnityEngine.Networking;
1+
using System.Text;
2+
using System.Collections;
3+
using UnityEngine;
4+
using UnityEngine.Networking;
25

3-
namespace Proyecto26.Common.Extensions
6+
namespace Proyecto26.Common
47
{
58
public static class Extensions
69
{
+2-104
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,21 @@
11
using System;
2-
using System.Text;
32
using System.Collections;
43
using UnityEngine;
54
using UnityEngine.Networking;
6-
using Proyecto26.Common.Extensions;
5+
using Proyecto26.Common;
76

87
namespace Proyecto26
98
{
109
public static class HttpBase
1110
{
12-
private const string CONTENT_TYPE_HEADER = "Content-Type";
13-
private const string CONTENT_TYPE_JSON = "application/json";
14-
1511
public static IEnumerator CreateRequestAndRetry(RequestHelper options, Action<RequestException, ResponseHelper> callback)
1612
{
1713
var retries = 0;
1814
do
1915
{
2016
using (var request = CreateRequest(options))
2117
{
22-
yield return SendWebRequest(request, options);
18+
yield return request.SendWebRequestWithOptions(options);
2319
var response = request.CreateWebResponse();
2420
if (request.IsValidRequest(options))
2521
{
@@ -117,103 +113,5 @@ public static IEnumerator DefaultUnityWebRequest<TResponse>(RequestHelper option
117113
});
118114
}
119115

120-
/// <summary>
121-
/// Send the web request to the server
122-
/// </summary>
123-
/// <returns>An UnityWebRequestAsyncOperation object.</returns>
124-
/// <param name="request">An UnityWebRequest object.</param>
125-
/// <param name="options">An options object.</param>
126-
public static IEnumerator SendWebRequest(UnityWebRequest request, RequestHelper options)
127-
{
128-
byte[] bodyRaw = options.BodyRaw;
129-
string contentType = string.Empty;
130-
if (!options.Headers.TryGetValue(CONTENT_TYPE_HEADER, out contentType))
131-
{
132-
contentType = CONTENT_TYPE_JSON;
133-
}
134-
if (options.Body != null || !string.IsNullOrEmpty(options.BodyString))
135-
{
136-
var bodyString = options.BodyString;
137-
if (options.Body != null)
138-
{
139-
bodyString = JsonUtility.ToJson(options.Body);
140-
}
141-
bodyRaw = Encoding.UTF8.GetBytes(bodyString.ToCharArray());
142-
}
143-
else if (options.SimpleForm != null && options.SimpleForm.Count > 0)
144-
{
145-
bodyRaw = UnityWebRequest.SerializeSimpleForm(options.SimpleForm);
146-
contentType = "application/x-www-form-urlencoded";
147-
}
148-
else if (options.FormSections != null && options.FormSections.Count > 0)
149-
{
150-
byte[] boundary = UnityWebRequest.GenerateBoundary();
151-
byte[] formSections = UnityWebRequest.SerializeFormSections(options.FormSections, boundary);
152-
byte[] terminate = Encoding.UTF8.GetBytes(string.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--"));
153-
bodyRaw = new byte[formSections.Length + terminate.Length];
154-
System.Buffer.BlockCopy(formSections, 0, bodyRaw, 0, formSections.Length);
155-
System.Buffer.BlockCopy(terminate, 0, bodyRaw, formSections.Length, terminate.Length);
156-
contentType = string.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary));
157-
}
158-
else if (options.FormData is WWWForm)
159-
{
160-
//The Content-Type header will be copied from the formData parameter
161-
contentType = string.Empty;
162-
}
163-
if (!string.IsNullOrEmpty(options.ContentType))
164-
{
165-
contentType = options.ContentType;
166-
}
167-
#if UNITY_2018_1_OR_NEWER
168-
if (options.CertificateHandler is CertificateHandler)
169-
request.certificateHandler = options.CertificateHandler;
170-
#endif
171-
if (options.UploadHandler is UploadHandler)
172-
request.uploadHandler = options.UploadHandler;
173-
if (bodyRaw != null)
174-
{
175-
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
176-
request.uploadHandler.contentType = contentType;
177-
}
178-
if (options.DownloadHandler is DownloadHandler)
179-
request.downloadHandler = options.DownloadHandler;
180-
else
181-
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
182-
if (!string.IsNullOrEmpty(contentType))
183-
{
184-
request.SetRequestHeader(CONTENT_TYPE_HEADER, contentType);
185-
}
186-
foreach (var header in RestClient.DefaultRequestHeaders)
187-
{
188-
request.SetRequestHeader(header.Key, header.Value);
189-
}
190-
foreach (var header in options.Headers)
191-
{
192-
request.SetRequestHeader(header.Key, header.Value);
193-
}
194-
if (options.Timeout.HasValue)
195-
{
196-
request.timeout = options.Timeout.Value;
197-
}
198-
if (options.ChunkedTransfer.HasValue)
199-
{
200-
request.chunkedTransfer = options.ChunkedTransfer.Value;
201-
}
202-
if (options.UseHttpContinue.HasValue)
203-
{
204-
request.useHttpContinue = options.UseHttpContinue.Value;
205-
}
206-
if (options.RedirectLimit.HasValue)
207-
{
208-
request.redirectLimit = options.RedirectLimit.Value;
209-
}
210-
options.Request = request;
211-
#if UNITY_2017_2_OR_NEWER
212-
yield return request.SendWebRequest();
213-
#else
214-
yield return request.Send();
215-
#endif
216-
}
217-
218116
}
219117
}

0 commit comments

Comments
 (0)