server.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // @ts-ignore -- generated package
  2. import "src/utils/environment";
  3. import * as sapper from "@sapper/server"; // eslint-disable-line import/no-unresolved
  4. import compression from "compression";
  5. import express, { Express } from "express";
  6. import session from "cookie-session";
  7. // @ts-ignore -- doesn't package its own types until 1.0.0-next.6
  8. import sirv from "sirv";
  9. import { createConnection, getConnectionOptions } from "typeorm";
  10. import { DB_ENTITIES } from "@shared/db/entities";
  11. import { logger } from "./utils/logging";
  12. const PORT = process.env.PORT; // eslint-disable-line prefer-destructuring
  13. // @ts-ignore -- creates a warning after `rollup-plugin-replace` (set up in `rollup.config.js`)
  14. // replaces `process.env.NODE_ENV` with `"production"` during `prod`
  15. const dev = process.env.NODE_ENV === "development";
  16. logger.info("Staring webserver");
  17. const key = process.env.WEB_COOKIE_KEY;
  18. if (!key) {
  19. logger.error("WEB_COOKIE_KEY is not set, cannot run!");
  20. process.exit();
  21. }
  22. const createSapperServer = async (): Promise<Express> => {
  23. await createConnection({
  24. ...await getConnectionOptions(),
  25. entities: DB_ENTITIES,
  26. });
  27. const app = express();
  28. app.use(
  29. session({
  30. secret: key,
  31. name: "session",
  32. }),
  33. compression({ threshold: 0 }),
  34. sirv("static", { dev }),
  35. sapper.middleware({
  36. session: (req) => ({
  37. userId: req.session?.userId,
  38. }),
  39. }),
  40. );
  41. return app;
  42. };
  43. createSapperServer().then((app) => {
  44. app.listen(PORT, (err?: any): void => { // eslint-disable-line
  45. if (err) logger.error("Error on webserver: %s", err);
  46. });
  47. });
  48. export { sapper };