diff --git a/src/Program.cs b/src/Program.cs index 84edc16..9e98cb4 100644 --- a/src/Program.cs +++ b/src/Program.cs @@ -1,5 +1,3 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; using Microsoft.Data.Sqlite; var builder = WebApplication.CreateBuilder(args); @@ -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(); @@ -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(0), contentType: "image/png"); + + return Results.NoContent(); }); app.UseHttpsRedirection();