sequelize.js 2.1 KB

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