Skip to content

Commit

Permalink
Avoid buffering the content before streaming to the response body
Browse files Browse the repository at this point in the history
  • Loading branch information
gfoidl authored and oskardudycz committed Nov 23, 2023
1 parent d682b61 commit b5bfaf6
Showing 1 changed file with 3 additions and 19 deletions.
22 changes: 3 additions & 19 deletions src/Marten.AspNetCore/QueryableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,10 @@ public static async Task WriteArray<T>(
int onFoundStatus = 200
)
{
var stream = new MemoryStream();
await queryable.StreamJsonArray(stream, context.RequestAborted).ConfigureAwait(false);

context.Response.StatusCode = onFoundStatus;
context.Response.ContentLength = stream.Length;
context.Response.ContentType = contentType;

stream.Position = 0;
await stream.CopyToAsync(context.Response.Body, context.RequestAborted).ConfigureAwait(false);
await queryable.StreamJsonArray(context.Response.Body, context.RequestAborted).ConfigureAwait(false);
}

/// <summary>
Expand Down Expand Up @@ -266,15 +261,10 @@ public static async Task WriteArray<TDoc, TOut>(
int onFoundStatus = 200
)
{
var stream = new MemoryStream();
await session.StreamJsonMany(query, stream, context.RequestAborted).ConfigureAwait(false);

context.Response.StatusCode = onFoundStatus;
context.Response.ContentLength = stream.Length;
context.Response.ContentType = contentType;

stream.Position = 0;
await stream.CopyToAsync(context.Response.Body, context.RequestAborted).ConfigureAwait(false);
await session.StreamJsonMany(query, context.Response.Body, context.RequestAborted).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -285,7 +275,6 @@ public static async Task WriteArray<TDoc, TOut>(
/// <param name="context"></param>
/// <param name="contentType"></param>
/// <param name="onFoundStatus">Defaults to 200</param>
/// <returns></returns>
public static async Task WriteJson(
this IQuerySession session,
string sql,
Expand All @@ -295,14 +284,9 @@ public static async Task WriteJson(
params object[] parameters
)
{
var stream = new MemoryStream();
_ = await session.StreamJson<int>(stream, context.RequestAborted, sql, parameters).ConfigureAwait(false);

context.Response.StatusCode = onFoundStatus;
context.Response.ContentLength = stream.Length;
context.Response.ContentType = contentType;

stream.Position = 0;
await stream.CopyToAsync(context.Response.Body, context.RequestAborted).ConfigureAwait(false);
await session.StreamJson<int>(context.Response.Body, context.RequestAborted, sql, parameters).ConfigureAwait(false);
}
}

0 comments on commit b5bfaf6

Please sign in to comment.