DbModule.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. namespace NancyModules
  2. {
  3. using System;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Linq;
  7. using Dapper;
  8. using MySql.Data.MySqlClient;
  9. using Nancy;
  10. public class DbModule : NancyModule
  11. {
  12. public static string MYSQL_CONNECTION_STRING;
  13. static DbModule()
  14. {
  15. MYSQL_CONNECTION_STRING = ConfigurationManager.AppSettings["ConnectionString.MySQL"];
  16. }
  17. public DbModule() : base("/db")
  18. {
  19. Get["/{queries?1}"] = paramz =>
  20. {
  21. var queries = (int)paramz.queries;
  22. var random = new Random();
  23. using (var db = new MySqlConnection(MYSQL_CONNECTION_STRING))
  24. {
  25. db.Open();
  26. if (queries == 1)
  27. return GetRandomWorld(db, random);
  28. else
  29. {
  30. var worldCount = queries > 500 ? 500 : queries;
  31. worldCount = worldCount < 1 ? 1 : worldCount;
  32. // NOTE: Experiment with running the DB requests in parallel, on both Mono and Windows CLRs.
  33. var worlds = new World[worldCount];
  34. for (int i = 0; i < worldCount; ++i)
  35. {
  36. worlds[i] = GetRandomWorld(db, random);
  37. }
  38. return worlds;
  39. }
  40. }
  41. };
  42. }
  43. private World GetRandomWorld(IDbConnection db, Random random)
  44. {
  45. var id = random.Next(1, 10001);
  46. return db.Query<World>("SELECT id, randomNumber FROM world WHERE id = @id", new { id = id }).Single();
  47. }
  48. }
  49. public class World
  50. {
  51. public int id { get; set; }
  52. public int randomNumber { get; set; }
  53. }
  54. }