| 1 | import express from "express";
|
| 2 | import cors from "cors";
|
| 3 | import bodyParser from "body-parser";
|
| 4 | import morgan from "morgan";
|
| 5 | import mainRouter from "@app/routes/main";
|
| 6 | import userRouter from "@app/routes/users";
|
| 7 | import authRouter from "@app/routes/auth";
|
| 8 | import moodRouter from "@app/routes/moods";
|
| 9 | import triggerRouter from "@app/routes/triggers";
|
| 10 | import sleepRecordRouter from "@app/routes/sleepRecords";
|
| 11 | import insightRouter from "@app/routes/insights";
|
| 12 | import { errorHandler } from "@app/middleware/errorHandler";
|
| 13 | import { PrismaClient } from "@prisma/client";
|
| 14 | import {
|
| 15 | bootWorkers,
|
| 16 | closeAllWorkers,
|
| 17 | closeAllQueues,
|
| 18 | scheduleInsights,
|
| 19 | } from "@app/lib/queue";
|
| 20 |
|
| 21 | import pino from "pino";
|
| 22 | import pinoHttp from "pino-http";
|
| 23 | import path from "path";
|
| 24 |
|
| 25 | export function createApp() {
|
| 26 | const app = express();
|
| 27 | bootWorkers();
|
| 28 | scheduleInsights();
|
| 29 |
|
| 30 | // Configure CORS
|
| 31 | app.use(
|
| 32 | cors({
|
| 33 | origin: process.env.FRONTEND_URL || "*",
|
| 34 | credentials: true,
|
| 35 | }),
|
| 36 | );
|
| 37 |
|
| 38 | app.use(bodyParser.json());
|
| 39 |
|
| 40 | const isDev = process.env.NODE_ENV !== "production";
|
| 41 |
|
| 42 | const logger = pino({
|
| 43 | level: process.env.LOG_LEVEL || "info",
|
| 44 | ...(isDev && {
|
| 45 | transport: {
|
| 46 | target: "pino-pretty",
|
| 47 | options: {
|
| 48 | colorize: true,
|
| 49 | singleLine: false,
|
| 50 | messageFormat: "{if levelLabel}{levelLabel} - {end}{msg}",
|
| 51 | },
|
| 52 | },
|
| 53 | }),
|
| 54 | });
|
| 55 |
|
| 56 | // Use pino-http for HTTP logging (better than Morgan for structured logs)
|
| 57 | app.use(pinoHttp({ logger }));
|
| 58 |
|
| 59 | app.use("/users", userRouter);
|
| 60 | app.use("/auth", authRouter);
|
| 61 | app.use("/moods", moodRouter);
|
| 62 | app.use("/sleep_records", sleepRecordRouter);
|
| 63 | app.use("/triggers", triggerRouter);
|
| 64 | app.use("/insights", insightRouter);
|
| 65 |
|
| 66 | app.use(errorHandler); // always last
|
| 67 |
|
| 68 | // TODO: flesh the actual page here
|
| 69 | app.use(express.static(path.join(__dirname, "./static")));
|
| 70 | app.get(/.*/, (req, res) => {
|
| 71 | res.sendFile(path.join(__dirname, "./static/index.html"));
|
| 72 | });
|
| 73 |
|
| 74 | process.on("SIGTERM", shutdown);
|
| 75 | process.on("SIGINT", shutdown);
|
| 76 |
|
| 77 | return app;
|
| 78 | }
|
| 79 |
|
| 80 | const shutdown = async () => {
|
| 81 | await Promise.all([closeAllWorkers(), closeAllQueues()]);
|
| 82 | process.exit(0);
|
| 83 | };
|