mongodb-raw.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const h = require('../helper');
  2. const async = require('async');
  3. const MongoClient = require('mongodb').MongoClient;
  4. const collections = {
  5. World: null,
  6. Fortune: null
  7. };
  8. MongoClient.connect('mongodb://TFB-database/hello_world?maxPoolSize=5', (err, db) => {
  9. // do nothing if there is err connecting to db
  10. collections.World = db.collection('world');
  11. collections.Fortune = db.collection('fortune');
  12. });
  13. const mongodbRandomWorld = (callback) => {
  14. collections.World.findOne({
  15. id: h.randomTfbNumber()
  16. }, (err, world) => {
  17. world._id = undefined; // remove _id from query response
  18. callback(err, world);
  19. });
  20. };
  21. const mongodbGetAllFortunes = (callback) => {
  22. collections.Fortune.find().toArray((err, fortunes) => {
  23. callback(err, fortunes);
  24. })
  25. };
  26. const mongodbDriverUpdateQuery = (callback) => {
  27. collections.World.findOne({id: h.randomTfbNumber()}, (err, world) => {
  28. world.randomNumber = h.randomTfbNumber();
  29. collections.World.update({id: world.id}, world, (err, updated) => {
  30. callback(err, { id: world.id, randomNumber: world.randomNumber } );
  31. });
  32. });
  33. };
  34. module.exports = {
  35. SingleQuery: (req, res) => {
  36. mongodbRandomWorld((err, result) => {
  37. if (err) { return process.exit(1) }
  38. h.addTfbHeaders(res, 'json');
  39. res.end(JSON.stringify(result));
  40. });
  41. },
  42. MultipleQueries: (queries, req, res) => {
  43. const queryFunctions = h.fillArray(mongodbRandomWorld, queries);
  44. async.parallel(queryFunctions, (err, results) => {
  45. if (err) { return process.exit(1) }
  46. h.addTfbHeaders(res, 'json');
  47. res.end(JSON.stringify(results));
  48. });
  49. },
  50. Fortunes: (req, res) => {
  51. mongodbGetAllFortunes((err, fortunes) => {
  52. if (err) { return process.exit(1) }
  53. fortunes.push(h.additionalFortune());
  54. fortunes.sort(function (a, b) {
  55. return a.message.localeCompare(b.message);
  56. });
  57. h.addTfbHeaders(res, 'html');
  58. res.end(h.fortunesTemplate({
  59. fortunes: fortunes
  60. }));
  61. });
  62. },
  63. Updates: (queries, req, res) => {
  64. const queryFunctions = h.fillArray(mongodbDriverUpdateQuery, queries);
  65. async.parallel(queryFunctions, (err, results) => {
  66. if (err) { return process.exit(1) }
  67. h.addTfbHeaders(res, 'json');
  68. res.end(JSON.stringify(results));
  69. });
  70. }
  71. };