Skip to content

Commit

Permalink
com.utilities.rest 2.5.3 (#69)
Browse files Browse the repository at this point in the history
- Reformat response debug to json
- Added RequestBody to response debug
  • Loading branch information
StephenHodgson committed Feb 25, 2024
1 parent 08c0189 commit 7780453
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 34 deletions.
4 changes: 2 additions & 2 deletions Runtime/DownloadHandlerCallback.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected override bool ReceiveData(byte[] unprocessedData, int dataLength)
var buffer = new byte[bytesToRead];
var bytesRead = stream.Read(buffer, 0, (int)bytesToRead);
streamPosition += bytesRead;
OnDataReceived?.Invoke(new Response(webRequest.url, webRequest.method, true, null, buffer, webRequest.responseCode, webRequest.GetResponseHeaders()));
OnDataReceived?.Invoke(new Response(webRequest.url, webRequest.method, null, true, null, buffer, webRequest.responseCode, webRequest.GetResponseHeaders()));
}
}
catch (Exception e)
Expand All @@ -69,7 +69,7 @@ protected override void CompleteContent()
var buffer = new byte[StreamOffset];
var bytesRead = stream.Read(buffer);
streamPosition += bytesRead;
OnDataReceived?.Invoke(new Response(webRequest.url, webRequest.method, true, null, buffer, webRequest.responseCode, webRequest.GetResponseHeaders()));
OnDataReceived?.Invoke(new Response(webRequest.url, webRequest.method, null, true, null, buffer, webRequest.responseCode, webRequest.GetResponseHeaders()));
}
}
catch (Exception e)
Expand Down
108 changes: 97 additions & 11 deletions Runtime/Response.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;

Expand All @@ -15,6 +18,11 @@ public class Response
/// </summary>
public string Request { get; }

/// <summary>
/// The original request body.
/// </summary>
public string RequestBody { get; }

/// <summary>
/// The request method that prompted the response.
/// </summary>
Expand Down Expand Up @@ -55,12 +63,38 @@ public class Response
/// </summary>
/// <param name="request">The request that prompted the response.</param>
/// <param name="method">The request method that prompted the response.</param>
/// <param name="requestBody">The request body that prompted the response.</param>
/// <param name="successful">Was the REST call successful?</param>
/// <param name="body">Response body from the resource.</param>
/// <param name="data">Response data from the resource.</param>
/// <param name="responseCode">Response code from the resource.</param>
/// <param name="headers">Response headers from the resource.</param>
/// <param name="error">Optional, error message from the resource.</param>
public Response(string request, string method, string requestBody, bool successful, string body, byte[] data, long responseCode, IReadOnlyDictionary<string, string> headers, string error = null)
{
Request = request;
RequestBody = requestBody;
Method = method;
Successful = successful;
Body = body;
Data = data;
Code = responseCode;
Headers = headers;
Error = error;
}

/// <summary>
/// Constructor.
/// </summary>
/// <param name="request">The request that prompted the response.</param>
/// <param name="method">The request method that prompted the response.</param>
/// <param name="successful">Was the REST call successful?</param>
/// <param name="body">Response body from the resource.</param>
/// <param name="data">Response data from the resource.</param>
/// <param name="responseCode">Response code from the resource.</param>
/// <param name="headers">Response headers from the resource.</param>
/// <param name="error">Optional, error message from the resource.</param>
[Obsolete("Use new .ctr with requestBody")]
public Response(string request, string method, bool successful, string body, byte[] data, long responseCode, IReadOnlyDictionary<string, string> headers, string error = null)
{
Request = request;
Expand Down Expand Up @@ -88,35 +122,87 @@ public string ToString(string methodName)
debugMessage.Append(!Successful ? " <color=\"red\">Failed!</color>" : " <color=\"green\">Success!</color>");
debugMessage.Append("\n");

if (Headers != null)
var debugMessageObject = new Dictionary<string, Dictionary<string, object>>
{
debugMessage.AppendLine("[Headers]");
["request"] = new()
{
["url"] = Request
}
};

foreach (var header in Headers)
if (!string.IsNullOrWhiteSpace(RequestBody))
{
try
{
debugMessageObject["request"]["body"] = JObject.Parse(RequestBody);
}
catch
{
debugMessage.AppendLine($"{header.Key}: {header.Value}");
debugMessageObject["request"]["body"] = RequestBody;
}
}

debugMessageObject["response"] = new()
{
["code"] = Code,
};

if (Headers != null)
{
debugMessageObject["response"]["headers"] = Headers;
}

if (Data is { Length: > 0 })
{
debugMessage.AppendLine($"[Data] {Data.Length} bytes");
debugMessageObject["response"]["data"] = Data.Length;
}

if (!string.IsNullOrWhiteSpace(Body))
{
debugMessage.AppendLine("[Body]");
debugMessage.Append(Body);
debugMessage.Append("\n");
var parts = Body.Split("data: ");

if (parts.Length > 0)
{
debugMessageObject["response"]["body"] = new JArray();

foreach (var part in parts)
{
if (string.IsNullOrWhiteSpace(part) || part.Contains("[DONE]\n\n")) { continue; }

try
{
((JArray)debugMessageObject["response"]["body"]).Add(JObject.Parse(part));
}
catch
{
((JArray)debugMessageObject["response"]["body"]).Add(new JValue(part));
}
}
}
else
{
try
{
debugMessageObject["response"]["body"] = JObject.Parse(Body);
}
catch
{
debugMessageObject["response"]["body"] = Body;
}
}
}

if (!string.IsNullOrWhiteSpace(Error))
{
debugMessage.AppendLine("[Errors]");
debugMessage.Append(Error);
debugMessage.Append("\n");
debugMessageObject["response"]["error"] = Error;
}

var jsonSettings = new JsonSerializerSettings
{
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii,
Formatting = Formatting.Indented
};
debugMessage.Append(JsonConvert.SerializeObject(debugMessageObject, jsonSettings));
return debugMessage.ToString();
}
}
Expand Down
44 changes: 24 additions & 20 deletions Runtime/Rest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1142,18 +1142,22 @@ async void CallbackThread()
#pragma warning restore CS4014
}

try
var requestBody = string.Empty;

if (hasUpload && webRequest.uploadHandler != null)
{
if (parameters is { Debug: true })
{
Debug.Log($"[{webRequest.method}] {webRequest.url}");
}
requestBody = webRequest.uploadHandler.data is { Length: > 0 }
? Encoding.UTF8.GetString(webRequest.uploadHandler.data)
: string.Empty;
}

try
{
await webRequest.SendWebRequest();
}
catch (Exception e)
{
return new Response(webRequest.url, webRequest.method, false, $"{nameof(Rest)}.{nameof(SendAsync)}::{nameof(UnityWebRequest.SendWebRequest)} Failed!", null, -1, null, e.ToString());
return new Response(webRequest.url, webRequest.method, requestBody, false, $"{nameof(Rest)}.{nameof(SendAsync)}::{nameof(UnityWebRequest.SendWebRequest)} Failed!", null, -1, null, e.ToString());
}

parameters?.Progress?.Report(new Progress(webRequest.downloadedBytes, webRequest.downloadedBytes, 100f, 0, Progress.DataUnit.b));
Expand All @@ -1166,13 +1170,13 @@ UnityWebRequest.Result.ConnectionError or
{
return webRequest.downloadHandler switch
{
DownloadHandlerFile => new Response(webRequest.url, webRequest.method, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerTexture => new Response(webRequest.url, webRequest.method, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerAudioClip => new Response(webRequest.url, webRequest.method, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerAssetBundle => new Response(webRequest.url, webRequest.method, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerBuffer bufferDownloadHandler => new Response(webRequest.url, webRequest.method, false, bufferDownloadHandler.text, bufferDownloadHandler.data, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerScript scriptDownloadHandler => new Response(webRequest.url, webRequest.method, false, scriptDownloadHandler.text, scriptDownloadHandler.data, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
_ => new Response(webRequest.url, webRequest.method, false, webRequest.responseCode == 401 ? "Invalid Credentials" : webRequest.downloadHandler?.text, webRequest.downloadHandler?.data, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}")
DownloadHandlerFile => new Response(webRequest.url, webRequest.method, requestBody, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerTexture => new Response(webRequest.url, webRequest.method, requestBody, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerAudioClip => new Response(webRequest.url, webRequest.method, requestBody, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerAssetBundle => new Response(webRequest.url, webRequest.method, requestBody, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerBuffer bufferDownloadHandler => new Response(webRequest.url, webRequest.method, requestBody, false, bufferDownloadHandler.text, bufferDownloadHandler.data, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerScript scriptDownloadHandler => new Response(webRequest.url, webRequest.method, requestBody, false, scriptDownloadHandler.text, scriptDownloadHandler.data, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
_ => new Response(webRequest.url, webRequest.method, requestBody, false, webRequest.responseCode == 401 ? "Invalid Credentials" : webRequest.downloadHandler?.text, webRequest.downloadHandler?.data, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}")
};
}

Expand All @@ -1183,13 +1187,13 @@ UnityWebRequest.Result.ConnectionError or

return webRequest.downloadHandler switch
{
DownloadHandlerFile => new Response(webRequest.url, webRequest.method, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerTexture => new Response(webRequest.url, webRequest.method, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerAudioClip => new Response(webRequest.url, webRequest.method, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerAssetBundle => new Response(webRequest.url, webRequest.method, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerBuffer bufferDownloadHandler => new Response(webRequest.url, webRequest.method, true, bufferDownloadHandler.text, bufferDownloadHandler.data, webRequest.responseCode, responseHeaders),
DownloadHandlerScript scriptDownloadHandler => new Response(webRequest.url, webRequest.method, true, scriptDownloadHandler.text, scriptDownloadHandler.data, webRequest.responseCode, responseHeaders),
_ => new Response(webRequest.url, webRequest.method, true, webRequest.downloadHandler?.text, webRequest.downloadHandler?.data, webRequest.responseCode, responseHeaders)
DownloadHandlerFile => new Response(webRequest.url, webRequest.method, requestBody, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerTexture => new Response(webRequest.url, webRequest.method, requestBody, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerAudioClip => new Response(webRequest.url, webRequest.method, requestBody, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerAssetBundle => new Response(webRequest.url, webRequest.method, requestBody, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerBuffer bufferDownloadHandler => new Response(webRequest.url, webRequest.method, requestBody, true, bufferDownloadHandler.text, bufferDownloadHandler.data, webRequest.responseCode, responseHeaders),
DownloadHandlerScript scriptDownloadHandler => new Response(webRequest.url, webRequest.method, requestBody, true, scriptDownloadHandler.text, scriptDownloadHandler.data, webRequest.responseCode, responseHeaders),
_ => new Response(webRequest.url, webRequest.method, requestBody, true, webRequest.downloadHandler?.text, webRequest.downloadHandler?.data, webRequest.responseCode, responseHeaders)
};

void SendServerEventCallback(bool isEnd)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"displayName": "Utilities.Rest",
"description": "This package contains useful RESTful utilities for the Unity Game Engine.",
"keywords": [],
"version": "2.5.2",
"version": "2.5.3",
"unity": "2021.3",
"documentationUrl": "https://github.com/RageAgainstThePixel/com.utilities.rest#documentation",
"changelogUrl": "https://github.com/RageAgainstThePixel/com.utilities.rest/releases",
Expand Down

0 comments on commit 7780453

Please sign in to comment.