sequelize-postgres.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Connects to Postgres 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: 'postgres',
  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) => reply(world).header('Server', 'hapi')),
  38. MultipleQueries: (req, reply) => {
  39. const queries = h.getQueries(req),
  40. worldPromises = [];
  41. for (let i = 0; i < queries; i++) {
  42. worldPromises.push(randomWorldPromise());
  43. }
  44. Promise.all(worldPromises)
  45. .then((worlds) => reply(worlds).header('Server', 'hapi'));
  46. },
  47. Fortunes: (req, reply) => {
  48. Fortunes.findAll().then((fortunes) => {
  49. fortunes.push(h.additionalFortune());
  50. fortunes.sort((a, b) => a.message.localeCompare(b.message));
  51. reply.view('fortunes', { fortunes: fortunes })
  52. .header('Content-Type', 'text/html')
  53. .header('Server', 'hapi');
  54. }).catch((err) => process.exit(1));
  55. },
  56. Updates: (req, reply) => {
  57. const queries = h.getQueries(req),
  58. worldPromises = [];
  59. for (let i = 0; i < queries; i++) {
  60. worldPromises.push(randomWorldPromise());
  61. }
  62. const worldUpdate = (world) => {
  63. world.randomNumber = h.randomTfbNumber();
  64. return Worlds.update(
  65. {randomNumber: world.randomNumber},
  66. {where: {id: world.id}}
  67. )
  68. .then((results) => world)
  69. .catch((err) => process.exit(1));
  70. };
  71. Promise
  72. .all(worldPromises)
  73. .map((world) => worldUpdate(world))
  74. .then((updated) => reply(updated).header('Server', 'hapi'))
  75. .catch((err) => process.exit(1));
  76. }
  77. };