sequelize.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Connects to MySQL using the sequelize driver
  2. // Handles related routes
  3. const Promise = require('bluebird');
  4. const h = require('../helper');
  5. const Sequelize = require('sequelize');
  6. const sequelize = new Sequelize('hello_world', 'benchmarkdbuser', 'benchmarkdbpass', {
  7. host: 'TFB-database',
  8. dialect: 'mysql',
  9. logging: false
  10. });
  11. const Worlds = sequelize.define('World', {
  12. id: {
  13. type: 'Sequelize.INTEGER',
  14. primaryKey: true
  15. },
  16. randomNumber: { type: 'Sequelize.INTEGER' }
  17. }, {
  18. timestamps: false,
  19. freezeTableName: true
  20. });
  21. const Fortunes = sequelize.define('Fortune', {
  22. id: {
  23. type: 'Sequelize.INTEGER',
  24. primaryKey: true
  25. },
  26. message: { type: 'Sequelize.STRING' }
  27. }, {
  28. timestamps: false,
  29. freezeTableName: true
  30. });
  31. const randomWorldPromise = () =>
  32. Worlds.findOne({ where: { id: h.randomTfbNumber() } })
  33. .then((results) => results)
  34. .catch((err) => process.exit(1));
  35. module.exports = {
  36. SingleQuery: (req, reply) => {
  37. randomWorldPromise().then((world) => {
  38. reply(world)
  39. .header('Server', 'hapi');
  40. })
  41. },
  42. MultipleQueries: (req, reply) => {
  43. const queries = h.getQueries(req);
  44. const worldPromises = [];
  45. for (let i = 0; i < queries; i++) {
  46. worldPromises.push(randomWorldPromise());
  47. }
  48. Promise.all(worldPromises).then((worlds) =>
  49. reply(worlds).header('Server', 'hapi'));
  50. },
  51. Fortunes: (req, reply) => {
  52. Fortunes.findAll().then((fortunes) => {
  53. fortunes.push(h.additionalFortune());
  54. fortunes.sort((a, b) => a.message.localeCompare(b.message));
  55. reply.view('fortunes', { fortunes })
  56. .header('Content-Type', 'text/html')
  57. .header('Server', 'hapi');
  58. }).catch((err) => process.exit(1));
  59. },
  60. Updates: (req, reply) => {
  61. const queries = h.getQueries(req);
  62. const worldPromises = [];
  63. for (let i = 0; i < queries; i++) {
  64. worldPromises.push(randomWorldPromise());
  65. }
  66. const worldUpdate = (world) => {
  67. world.randomNumber = h.randomTfbNumber();
  68. return Worlds.update(
  69. { randomNumber: world.randomNumber },
  70. { where: { id: world.id } }
  71. )
  72. .then((results) => world)
  73. .catch((err) => process.exit(1));
  74. };
  75. Promise
  76. .all(worldPromises)
  77. .map((world) => worldUpdate(world))
  78. .then((updated) => reply(updated).header('Server', 'hapi'))
  79. .catch((e) => process.exit(1));
  80. }
  81. };