server.mjs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import express from "express";
  2. import {
  3. generateRandomNumber,
  4. getQueriesCount,
  5. handleError,
  6. escape,
  7. jsonSerializer,
  8. worldObjectSerializer,
  9. sortByMessage,
  10. writeResponse,
  11. headerTypes,
  12. GREETING,
  13. } from "./utils.mjs";
  14. let db;
  15. const { DATABASE } = process.env;
  16. if (DATABASE) db = await import(`./database/${DATABASE}.mjs`);
  17. const extra = { id: 0, message: "Additional fortune added at request time." };
  18. const app = express();
  19. app.get("/plaintext", (req, res) => {
  20. writeResponse(res, GREETING, headerTypes["plain"]);
  21. });
  22. app.get("/json", (req, res) => {
  23. writeResponse(res, jsonSerializer({ message: GREETING }));
  24. });
  25. if (db) {
  26. app.get("/db", async (req, res) => {
  27. try {
  28. const row = await db.find(generateRandomNumber());
  29. writeResponse(res, worldObjectSerializer(row));
  30. } catch (error) {
  31. handleError(error, res);
  32. }
  33. });
  34. app.get("/queries", async (req, res) => {
  35. try {
  36. const queriesCount = getQueriesCount(req);
  37. const databaseJobs = new Array(queriesCount)
  38. .fill()
  39. .map(() => db.find(generateRandomNumber()));
  40. const worldObjects = await Promise.all(databaseJobs);
  41. writeResponse(res, JSON.stringify(worldObjects));
  42. } catch (error) {
  43. handleError(error, res);
  44. }
  45. });
  46. app.get("/fortunes", async (req, res) => {
  47. try {
  48. const rows = [extra, ...(await db.fortunes())];
  49. sortByMessage(rows);
  50. const n = rows.length;
  51. let html = "",
  52. i = 0;
  53. for (; i < n; i++) {
  54. html += `<tr><td>${rows[i].id}</td><td>${escape(
  55. rows[i].message
  56. )}</td></tr>`;
  57. }
  58. writeResponse(
  59. res,
  60. `<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>${html}</table></body></html>`,
  61. headerTypes["html"]
  62. );
  63. } catch (error) {
  64. handleError(error, res);
  65. }
  66. });
  67. app.get("/updates", async (req, res) => {
  68. try {
  69. const queriesCount = getQueriesCount(req);
  70. const databaseJobs = new Array(queriesCount);
  71. for (let i = 0; i < queriesCount; i++) {
  72. databaseJobs[i] = db.find(generateRandomNumber());
  73. }
  74. const worldObjects = await Promise.all(databaseJobs);
  75. for (let i = 0; i < queriesCount; i++) {
  76. worldObjects[i].randomNumber = generateRandomNumber();
  77. }
  78. await db.bulkUpdate(worldObjects);
  79. writeResponse(res, JSON.stringify(worldObjects));
  80. } catch (error) {
  81. handleError(error, res);
  82. }
  83. });
  84. }
  85. app.all("*", (req, res) => {
  86. res.status(404).send("Not Found");
  87. });
  88. const host = process.env.HOST || "0.0.0.0";
  89. const port = parseInt(process.env.PORT || "8080");
  90. app.listen(port, host, () => {
  91. console.log(`Server running at http://${host}:${port}/`);
  92. });