HelloWorld.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. const {
  2. GET,
  3. validateParams
  4. } = require("chubbajs").routes.annotations;
  5. const Entities = require("html-entities").AllHtmlEntities;
  6. const World = require("../models/World");
  7. const Fortune = require("../models/Fortune");
  8. const entities = new Entities();
  9. function rando() {
  10. return Math.floor(Math.random() * 10000) + 1;
  11. }
  12. function sanitizeQueries(q) {
  13. if (!parseInt(q) || q < 1) return 1;
  14. if (q > 500) return 500;
  15. return q;
  16. }
  17. class HelloWorldController {
  18. @GET("*")
  19. async setServer(ctx) {
  20. ctx.res.set('Server', 'Express');
  21. }
  22. @GET("/plaintext")
  23. async plaintext(ctx) {
  24. ctx.res.set('Content-Type', 'text/plain');
  25. ctx.res.send("Hello, World!");
  26. }
  27. @GET("/json")
  28. async json(ctx) {
  29. ctx.res.json({ message: "Hello, World!"});
  30. }
  31. @GET("/db")
  32. async db(ctx) {
  33. const world = await new World(rando());
  34. ctx.res.json({ id: world.id, randomnumber: world.randomnumber });
  35. }
  36. @GET("/query")
  37. @validateParams({
  38. query: "queries",
  39. sanitize: sanitizeQueries
  40. })
  41. async query(ctx, { queries }) {
  42. const ret = [];
  43. for (let i = 0; i < queries; i++) {
  44. const world = await new World(rando());
  45. ret.push({ id: world.id, randomnumber: world.randomnumber });
  46. }
  47. ctx.res.json(ret);
  48. }
  49. @GET("/update")
  50. @validateParams({
  51. query: "queries",
  52. sanitize: sanitizeQueries
  53. })
  54. async update(ctx, { queries }) {
  55. const ret = [];
  56. for (let i = 0; i < queries; i++) {
  57. const world = await new World(rando());
  58. world.randomnumber = rando();
  59. await world.save();
  60. ret.push({ id: world.id, randomnumber: world.randomnumber });
  61. }
  62. ctx.res.json(ret);
  63. }
  64. @GET("/fortune")
  65. async fortune(ctx) {
  66. let fortunes = (await ctx.db.query(`SELECT * FROM "Fortune"`)).rows;
  67. const newFortune = new Fortune();
  68. newFortune.message = "Additional fortune added at request time.";
  69. newFortune.id = 0;
  70. fortunes.push(newFortune);
  71. fortunes.sort((a, b) => (a.message < b.message) ? -1 : 1);
  72. ctx.res.send(`<!DOCTYPE html>
  73. <html>
  74. <head>
  75. <title>Fortunes</title>
  76. </head>
  77. <body>
  78. <table>
  79. <tr>
  80. <th>id</th>
  81. <th>message</th>
  82. </tr>
  83. ${fortunes.map(f => `
  84. <tr>
  85. <td>${f.id}</td>
  86. <td>${entities.encode(f.message)}</td>
  87. </tr>
  88. `).join('')}
  89. </table>
  90. </body>
  91. </html>`);
  92. }
  93. }
  94. module.exports = HelloWorldController;