mongodb-raw.js 2.3 KB

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