3
1

index.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import express from "express";
  2. import cors from "cors";
  3. import path from "path";
  4. import morgan from "morgan";
  5. import socketio from "socket.io";
  6. import ascii from "./ascii";
  7. import db from "./db";
  8. const pg = require("pg");
  9. delete pg.native;
  10. import { connectUpstream } from "./joystream/ws";
  11. import { setupSocket } from "./socket";
  12. import { importEvents } from "./joystream";
  13. import { allowedOrigins, port } from "./config.json";
  14. const PORT: number = process.env.PORT ? +process.env.PORT : +port;
  15. const app = express();
  16. const server = app.listen(PORT, async () => {
  17. // handle arguments
  18. const args = process.argv.slice(2);
  19. if (args.length) return importEvents(args);
  20. console.log(`[Express] Listening on port ${PORT}`, ascii);
  21. const api = await connectUpstream();
  22. const io: any = socketio(server);
  23. setupSocket(io, api);
  24. });
  25. app.use(morgan("dev"));
  26. app.use(cors({ credentials: true, origin: allowedOrigins.split(",") }));
  27. // body parsing middleware
  28. app.use(express.json());
  29. app.use(express.urlencoded({ extended: true }));
  30. app.use(require("body-parser").text());
  31. app.use("/api", require("./api"));
  32. app.use(
  33. "/static",
  34. express.static(path.resolve(__dirname, "..", "build", "static"))
  35. );
  36. app.get("/manifest.json", (req: any, res: any) => {
  37. res.sendFile(path.resolve(__dirname, "..", "build", "manifest.json"));
  38. });
  39. app.get("/favicon.png", (req: any, res: any) => {
  40. res.sendFile(path.resolve(__dirname, "..", "build", "favicon.png"));
  41. });
  42. app.use("*", express.static(path.resolve(__dirname, "..", "build")));
  43. // error handling endware
  44. app.use((err: any, req: any, res: any, next: any) => {
  45. console.error(err);
  46. console.error(err.stack);
  47. res.status(err.status || 500).send(err.message || "Internal server error.");
  48. next();
  49. });