Skip to content

Commit

Permalink
Merge pull request #94 from dragonfruitnetwork/request-stream-types
Browse files Browse the repository at this point in the history
Request stream types
  • Loading branch information
aspriddell authored Nov 27, 2021
2 parents 57a7c41 + e4a5666 commit 18ef564
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
22 changes: 22 additions & 0 deletions DragonFruit.Common.Data.Tests/Requests/StreamTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// DragonFruit.Common Copyright 2021 DragonFruit Network
// Licensed under the MIT License. Please refer to the LICENSE file at the root of this project for details

using System.IO;
using System.Threading.Tasks;
using NUnit.Framework;

namespace DragonFruit.Common.Data.Tests.Requests
{
[TestFixture]
public class StreamTests : ApiTest
{
[Test]
public async Task TestStreamRequests()
{
var networkStream = await Client.PerformAsync<MemoryStream>("https://google.com");
var fileStream = await Client.PerformAsync<FileStream>("https://google.com");

Assert.AreEqual(networkStream.Length, fileStream.Length);
}
}
}
20 changes: 20 additions & 0 deletions DragonFruit.Common.Data/ApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
Expand Down Expand Up @@ -265,6 +266,25 @@ protected virtual async Task<T> ValidateAndProcess<T>(HttpResponseMessage respon
response.EnsureSuccessStatusCode();

using var stream = await response.Content.ReadAsStreamAsync();

if (typeof(Stream).IsAssignableFrom(typeof(T)))
{
Stream result;

if (typeof(T) == typeof(Stream) && response.Content.Headers.ContentLength < 80000 || typeof(T) == typeof(MemoryStream))
{
result = new MemoryStream();
}
else
{
result = File.Create(Path.GetTempFileName(), 4096, FileOptions.Asynchronous | FileOptions.SequentialScan | FileOptions.DeleteOnClose);
}

await stream.CopyToAsync(result).ConfigureAwait(false);
result.Seek(0, SeekOrigin.Begin);
return result as T;
}

return Serializer.Resolve<T>(DataDirection.In).Deserialize<T>(stream);
}

Expand Down

0 comments on commit 18ef564

Please sign in to comment.