DbModule.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. namespace Nancy.Benchmark
  2. {
  3. using System;
  4. using System.Data;
  5. using System.Threading.Tasks;
  6. using Dapper;
  7. using MySql.Data.MySqlClient;
  8. using Nancy;
  9. public class DbModule : NancyModule
  10. {
  11. private readonly string ConnectionString;
  12. /**
  13. * NOTE:
  14. * Return a single World objects as JSON, selected randomly from the World
  15. * table. Assume the table has 10,000 rows.
  16. */
  17. public DbModule(IAppConfiguration appConfig) : base("/db")
  18. {
  19. ConnectionString = appConfig.ConnectionString;
  20. Get("/{queries?1}", async args =>
  21. {
  22. var random = new Random();
  23. using (var db = new MySqlConnection(ConnectionString))
  24. {
  25. db.Open();
  26. return Response.AsJson(await GetRandomWorld(db, random));
  27. }
  28. });
  29. }
  30. private Task<World> GetRandomWorld(IDbConnection db, Random random)
  31. {
  32. var id = random.Next(1, 10001);
  33. return db.QueryFirstOrDefaultAsync<World>("SELECT id, randomNumber FROM world WHERE id = @id", new { id });
  34. }
  35. }
  36. public class World
  37. {
  38. public int id { get; set; }
  39. public int randomNumber { get; set; }
  40. }
  41. }