QueryModule.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 QueryModule : NancyModule
  11. {
  12. public static string MYSQL_CONNECTION_STRING;
  13. static QueryModule()
  14. {
  15. MYSQL_CONNECTION_STRING = ConfigurationManager.AppSettings["ConnectionString.MySQL"];
  16. }
  17. /**
  18. * Query:
  19. * Return a list of World objects as JSON, selected randomly from the World
  20. * table. Assume the table has 10,000 rows.
  21. */
  22. public QueryModule() : base("/query")
  23. {
  24. Get["/{queries?1}"] = paramz =>
  25. {
  26. var queries = (int)paramz.queries;
  27. var random = new Random();
  28. using (var db = new MySqlConnection(MYSQL_CONNECTION_STRING))
  29. {
  30. db.Open();
  31. if (queries == 1)
  32. return Response.AsJson( GetRandomWorld(db, random) );
  33. else
  34. {
  35. var worldCount = queries > 500 ? 500 : queries;
  36. worldCount = worldCount < 1 ? 1 : worldCount;
  37. // NOTE: Experiment with running the DB requests in parallel, on both Mono and Windows CLRs.
  38. var worlds = new World[worldCount];
  39. for (int i = 0; i < worldCount; ++i)
  40. {
  41. worlds[i] = GetRandomWorld(db, random);
  42. }
  43. return Response.AsJson( worlds );
  44. }
  45. }
  46. };
  47. Get["/{name}"] = paramz =>
  48. {
  49. var queries = (int)paramz.queries;
  50. var random = new Random();
  51. using (var db = new MySqlConnection(MYSQL_CONNECTION_STRING))
  52. {
  53. db.Open();
  54. if (queries == 1)
  55. return Response.AsJson( GetRandomWorld(db, random) );
  56. else
  57. {
  58. var worldCount = queries > 500 ? 500 : queries;
  59. worldCount = worldCount < 1 ? 1 : worldCount;
  60. // NOTE: Experiment with running the DB requests in parallel, on both Mono and Windows CLRs.
  61. var worlds = new World[worldCount];
  62. for (int i = 0; i < worldCount; ++i)
  63. {
  64. worlds[i] = GetRandomWorld(db, random);
  65. }
  66. return Response.AsJson( worlds );
  67. }
  68. }
  69. };
  70. }
  71. private World GetRandomWorld(IDbConnection db, Random random)
  72. {
  73. var id = random.Next(1, 10001);
  74. return db.Query<World>("SELECT id, randomNumber FROM world WHERE id = @id", new { id = id }).Single();
  75. }
  76. }
  77. }