Skip to content

Commit

Permalink
feat: support after hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
SilkageNet committed Jan 10, 2023
1 parent d4c5f51 commit 0c89ed1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
12 changes: 8 additions & 4 deletions Runtime/RestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,17 @@ public RestClient(string baseUrl) : this(new Uri(baseUrl))

public IEnumerator Do(RestRequest request, Action<RestResponse> completedAction)
{
Options.BeforeHooks?.ForEach(hook => hook(request));
using var webRequest = BuildUnityWebRequest(request);
yield return webRequest.SendWebRequest();
completedAction?.Invoke(new RestResponse(webRequest, request));
var response = new RestResponse(webRequest, request);
Options.AfterHooks?.ForEach(hook => hook(response));
completedAction?.Invoke(response);
}

public async Task<RestResponse> Do(RestRequest request)
{
Options.BeforeHooks?.ForEach(hook => hook(request));
var webRequest = BuildUnityWebRequest(request);
try
{
Expand All @@ -49,13 +53,13 @@ public async Task<RestResponse> Do(RestRequest request)
{
Debug.LogError($"do request exception: {e.Message}");
}

return new RestResponse(webRequest, request);
var response = new RestResponse(webRequest, request);
Options.AfterHooks?.ForEach(hook => hook(response));
return response;
}

private UnityWebRequest BuildUnityWebRequest(RestRequest request)
{
Options.BeforeHooks?.ForEach(hook => hook(request));
var url = request.BuildUrl(Options.BaseUrl);
var webRequest = new UnityWebRequest(url, request.Method.String());
webRequest.downloadHandler = request.DownloadHandler;
Expand Down
14 changes: 14 additions & 0 deletions Runtime/RestClientOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ public RestClientOptions(string baseUrl) : this(new Uri(baseUrl))
/// </summary>
public List<Action<RestRequest>> BeforeHooks { get; set; } = new();

/// <summary>
/// 请求执行后的Hooks
/// </summary>
public List<Action<RestResponse>> AfterHooks { get; set; } = new();

/// <summary>
/// 添加执行前Hook
/// </summary>
Expand All @@ -47,5 +52,14 @@ public void AddBeforeHook(Action<RestRequest> hook)
{
BeforeHooks.Add(hook);
}

/// <summary>
/// 添加执行后Hook
/// </summary>
/// <param name="hook"></param>
public void AddAfterHook(Action<RestResponse> hook)
{
AfterHooks.Add(hook);
}
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"com.cysharp.unitask": "2.3.3"
},
"displayName": "RestClient",
"version": "1.0.1",
"version": "1.0.2",
"unity": "2021.3",
"description": "Send HTTP requests in unity through Restful",
"keywords": [
Expand Down

0 comments on commit 0c89ed1

Please sign in to comment.