mongoose.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Connects to MongoDB using the mongoose driver
  2. // Handles related routes
  3. const Promise = require('bluebird');
  4. const h = require('../helper');
  5. // Can treat mongoose library as one that supports Promises
  6. // these methods will then have "-Async" appended to them.
  7. const Mongoose = Promise.promisifyAll(require('mongoose'));
  8. const connection = Mongoose.connect(
  9. 'mongodb://TFB-database/hello_world',
  10. { useMongoClient: true }
  11. );
  12. const WorldSchema = new Mongoose.Schema({
  13. id : Number,
  14. randomNumber: Number
  15. }, {
  16. collection: 'world'
  17. });
  18. const FortuneSchema = new Mongoose.Schema({
  19. id: Number,
  20. message: String
  21. }, {
  22. collection: 'fortune'
  23. });
  24. const Worlds = connection.model('World', WorldSchema);
  25. const Fortunes = connection.model('Fortune', FortuneSchema);
  26. const randomWorldPromise = () =>
  27. Worlds.findOneAsync({ id: h.randomTfbNumber() })
  28. .then((world) => world)
  29. .catch((err) => process.exit(1));
  30. const promiseAllFortunes = () =>
  31. Fortunes.findAsync({})
  32. .then((fortunes) => fortunes)
  33. .catch((err) => process.exit(1));
  34. const updateWorld = (world) =>
  35. Worlds
  36. .updateAsync(
  37. { id: world.randomNumber },
  38. { randomNumber: world.randomNumber }
  39. )
  40. .then((result) => world)
  41. .catch((err) => process.exit(1));
  42. module.exports = {
  43. SingleQuery: (req, reply) => {
  44. randomWorldPromise()
  45. .then((world) => {
  46. reply(world)
  47. .header('Server', 'hapi');
  48. });
  49. },
  50. MultipleQueries: (req, reply) => {
  51. const queries = h.getQueries(req);
  52. const worldPromises = h.fillArray(randomWorldPromise(), queries);
  53. Promise
  54. .all(worldPromises)
  55. .then((worlds) => {
  56. reply(worlds)
  57. .header('Server', 'hapi');
  58. });
  59. },
  60. Fortunes: (req, reply) => {
  61. promiseAllFortunes()
  62. .then((fortunes) => {
  63. fortunes.push(h.additionalFortune());
  64. fortunes.sort((a, b) => a.message.localeCompare(b.message));
  65. reply.view('fortunes', {
  66. fortunes: fortunes
  67. })
  68. .header('Content-Type', 'text/html')
  69. .header('Server', 'hapi');
  70. });
  71. },
  72. Updates: (req, reply) => {
  73. const queries = h.getQueries(req);
  74. const worldPromises = [];
  75. for (let i = 0; i < queries; i++) {
  76. worldPromises.push(randomWorldPromise());
  77. }
  78. Promise
  79. .all(worldPromises)
  80. .map((world) => {
  81. world.randomNumber = h.randomTfbNumber();
  82. return updateWorld(world);
  83. })
  84. .then((worlds) => {
  85. reply(worlds)
  86. .header('Server', 'hapi');
  87. });
  88. }
  89. };