I have an API that needs to return large lists of JSON data. I'm trying to stream it directly from the database to the client, to avoid hogging RAM on my web server. Would this be a good way to do it? (Seems to be working)
[HttpGet]
[Route("data")]
public IEnumerable<MappedDataDto> GetTestData()
{
var connection = new NpgsqlConnection(_connectionString);
connection.Open();
IEnumerable<RawDataDto> rawItems = connection.Query<RawDataDto>("SELECT * FROM sometable", buffered: true);
foreach (var rawItem in rawItems)
{
var mappedItem = Map(rawItem);
yield return mappedItem;
}
}
- Do I need to disponse the connection or will that automatically be taken care of? I can wrap it in i
using
block, since that throws an exception like "can't access a disposed object" - Would it be better to use some kind of stream instead of
yield return
?
EDIT: In my case we have a large legacy javascript web app that shows graphs and charts of data between two dates. The client downloads the entire dataset and does in memory calculations on the client to represent that data in different kind of ways (the users can create their own custom dashboards, so not every one uses the data in the same way).
Our problem is that when clients request a period with a lot of data, the memory consumption of our ASP.NET Core API increases a lot. So this is what we are trying to prevent.
Unfortunately, making any larger changes to the client would be very time consuming, so we are looking at what we can do on the API side instead.
So this is why I'm trying to figure out if there is a way to stream the data from the database through the API. So that there will need to be no changes on the client, and the memory consumtion of the API will not be as bad since it won't have to hold everything in memory.