|
| 1 | +using System.Text.Json; |
| 2 | + |
| 3 | +using GenHTTP.Modules.Webservices; |
| 4 | + |
| 5 | +using Npgsql; |
| 6 | + |
| 7 | +namespace genhttp.Tests; |
| 8 | + |
| 9 | +public class AsyncDatabase |
| 10 | +{ |
| 11 | + private static readonly NpgsqlDataSource? PgDataSource = OpenPgPool(); |
| 12 | + |
| 13 | + private static NpgsqlDataSource? OpenPgPool() |
| 14 | + { |
| 15 | + var dbUrl = Environment.GetEnvironmentVariable("DATABASE_URL"); |
| 16 | + if (string.IsNullOrEmpty(dbUrl)) return null; |
| 17 | + try |
| 18 | + { |
| 19 | + var uri = new Uri(dbUrl); |
| 20 | + var userInfo = uri.UserInfo.Split(':'); |
| 21 | + var connStr = $"Host={uri.Host};Port={uri.Port};Username={userInfo[0]};Password={userInfo[1]};Database={uri.AbsolutePath.TrimStart('/')};Maximum Pool Size=256;Minimum Pool Size=64;Multiplexing=true;No Reset On Close=true;Max Auto Prepare=4;Auto Prepare Min Usages=1"; |
| 22 | + var builder = new NpgsqlDataSourceBuilder(connStr); |
| 23 | + return builder.Build(); |
| 24 | + } |
| 25 | + catch { return null; } |
| 26 | + } |
| 27 | + |
| 28 | + [ResourceMethod] |
| 29 | + public async Task<ListWithCount<object>> Compute(int min = 10, int max = 50, int limit = 50) |
| 30 | + { |
| 31 | + if (PgDataSource == null) |
| 32 | + { |
| 33 | + return new ListWithCount<object>(new List<object>()); |
| 34 | + } |
| 35 | + |
| 36 | + await using var cmd = PgDataSource.CreateCommand( |
| 37 | + "SELECT id, name, category, price, quantity, active, tags, rating_score, rating_count FROM items WHERE price BETWEEN $1 AND $2 LIMIT $3"); |
| 38 | + |
| 39 | + cmd.Parameters.AddWithValue(min); |
| 40 | + cmd.Parameters.AddWithValue(max); |
| 41 | + cmd.Parameters.AddWithValue(limit); |
| 42 | + |
| 43 | + await using var reader = await cmd.ExecuteReaderAsync(); |
| 44 | + |
| 45 | + var items = new List<object>(limit); |
| 46 | + |
| 47 | + while (await reader.ReadAsync()) |
| 48 | + { |
| 49 | + items.Add(new |
| 50 | + { |
| 51 | + id = reader.GetInt32(0), |
| 52 | + name = reader.GetString(1), |
| 53 | + category = reader.GetString(2), |
| 54 | + price = reader.GetInt32(3), |
| 55 | + quantity = reader.GetInt32(4), |
| 56 | + active = reader.GetBoolean(5), |
| 57 | + tags = JsonSerializer.Deserialize<List<string>>(reader.GetString(6)), |
| 58 | + rating = new { score = reader.GetInt32(7), count = reader.GetInt32(8) }, |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + return new ListWithCount<object>(items); |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments