Skip to content

Commit

Permalink
fix: Removed blocking reader-call
Browse files Browse the repository at this point in the history
  • Loading branch information
philipp-meier committed Feb 26, 2023
1 parent bb6227a commit 0b96c52
Showing 1 changed file with 14 additions and 21 deletions.
35 changes: 14 additions & 21 deletions src/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.Sqlite;

var builder = WebApplication.CreateBuilder(args);
Expand All @@ -12,7 +10,7 @@
Mode = SqliteOpenMode.ReadOnly,
DataSource = mbtilesPath
};
builder.Services.AddScoped(_ => new SqliteConnection(connStr.ToString()));
builder.Services.AddTransient(_ => new SqliteConnection(connStr.ToString()));

var app = builder.Build();

Expand All @@ -23,28 +21,23 @@
app.UseHsts();
}

const string tileDataQuery = "SELECT tile_data FROM tiles WHERE zoom_level = $z AND tile_column = $x AND tile_row = $y";
app.MapGet("/{z:int}/{x:int}/{y:int}.png", async (HttpContext context, SqliteConnection db, int z, int x, int y) => {
context.Response.Headers.Add("Cache-Control", "max-age=58362, stale-while-revalidate=604800, stale-if-error=604800");

await db.OpenAsync();
using (var command = db.CreateCommand()) {
command.CommandText =
@"
SELECT tile_data
FROM tiles
WHERE zoom_level = $z AND tile_column = $x AND tile_row = $y
";
command.Parameters.AddWithValue("$z", z);
command.Parameters.AddWithValue("$x", x);
command.Parameters.AddWithValue("$y", y);

using (var reader = await command.ExecuteReaderAsync()) {
if (await reader.ReadAsync() && reader["tile_data"] is byte[] tileData)
return Results.File(tileData, contentType: "image/png");
else
return Results.NoContent();
}
}
await using var command = db.CreateCommand();

command.CommandText = tileDataQuery;
command.Parameters.AddWithValue("$z", z);
command.Parameters.AddWithValue("$x", x);
command.Parameters.AddWithValue("$y", y);

await using var reader = await command.ExecuteReaderAsync();
if (await reader.ReadAsync())
return Results.File(await reader.GetFieldValueAsync<byte[]>(0), contentType: "image/png");

return Results.NoContent();
});

app.UseHttpsRedirection();
Expand Down

0 comments on commit 0b96c52

Please sign in to comment.