mongoose.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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('mongodb://TFB-database/hello_world');
  9. const WorldSchema = new Mongoose.Schema({
  10. id : Number,
  11. randomNumber: Number
  12. }, {
  13. collection: 'world'
  14. });
  15. const FortuneSchema = new Mongoose.Schema({
  16. id: Number,
  17. message: String
  18. }, {
  19. collection: 'fortune'
  20. });
  21. const Worlds = connection.model('World', WorldSchema);
  22. const Fortunes = connection.model('Fortune', FortuneSchema);
  23. const randomWorldPromise = () =>
  24. Worlds.findOneAsync({ id: h.randomTfbNumber() })
  25. .then((world) => world)
  26. .catch((err) => process.exit(1));
  27. const promiseAllFortunes = () =>
  28. Fortunes.findAsync({})
  29. .then((fortunes) => fortunes)
  30. .catch((err) => process.exit(1));
  31. const updateWorld = (world) =>
  32. Worlds
  33. .updateAsync(
  34. { id: world.randomNumber },
  35. { randomNumber: world.randomNumber }
  36. )
  37. .then((result) => world)
  38. .catch((err) => process.exit(1));
  39. module.exports = {
  40. SingleQuery: (req, reply) => {
  41. randomWorldPromise()
  42. .then((world) => {
  43. reply(world)
  44. .header('Server', 'hapi');
  45. });
  46. },
  47. MultipleQueries: (req, reply) => {
  48. const queries = h.getQueries(req);
  49. const worldPromises = h.fillArray(randomWorldPromise(), queries);
  50. Promise
  51. .all(worldPromises)
  52. .then((worlds) => {
  53. reply(worlds)
  54. .header('Server', 'hapi');
  55. });
  56. },
  57. Fortunes: (req, reply) => {
  58. promiseAllFortunes()
  59. .then((fortunes) => {
  60. fortunes.push(h.additionalFortune());
  61. fortunes.sort((a, b) => a.message.localeCompare(b.message));
  62. reply.view('fortunes', {
  63. fortunes: fortunes
  64. })
  65. .header('Content-Type', 'text/html')
  66. .header('Server', 'hapi');
  67. });
  68. },
  69. Updates: (req, reply) => {
  70. const queries = h.getQueries(req);
  71. const worldPromises = [];
  72. for (let i = 0; i < queries; i++) {
  73. worldPromises.push(randomWorldPromise());
  74. }
  75. Promise
  76. .all(worldPromises)
  77. .map((world) => {
  78. world.randomNumber = h.randomTfbNumber();
  79. return updateWorld(world);
  80. })
  81. .then((worlds) => {
  82. reply(worlds)
  83. .header('Server', 'hapi');
  84. });
  85. }
  86. };