eletrotupi / tcc/ api/src/createApp.ts9263a7aaeb3c58782364439ba94afd8a3fe020b8
2.0 KB | 71 lines Raw
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 { errorHandler } from '@app/middleware/errorHandler';
12
import { PrismaClient } from '@prisma/client';
13
import { bootWorkers, closeAllWorkers, closeAllQueues } from '@app/lib/queue';
14
import pino from 'pino';
15
import pinoHttp from 'pino-http';
16
import path from 'path';
17

18
export function createApp() {
19
  const app = express();
20
  bootWorkers();
21

22
  // Configure CORS
23
  app.use(cors({
24
    origin: process.env.FRONTEND_URL || '*',
25
    credentials: true
26
  }));
27

28
  app.use(bodyParser.json());
29

30
  const isDev = process.env.NODE_ENV !== 'production';
31

32
  const logger = pino({
33
    level: process.env.LOG_LEVEL || 'info',
34
    ...(isDev && {
35
      transport: {
36
        target: 'pino-pretty',
37
        options: {
38
          colorize: true,
39
          singleLine: false,
40
          messageFormat: '{if levelLabel}{levelLabel} - {end}{msg}',
41
        },
42
      },
43
    }),
44
  });
45

46
  // Use pino-http for HTTP logging (better than Morgan for structured logs)
47
  app.use(pinoHttp({ logger }));
48

49
  app.use("/users", userRouter);
50
  app.use("/auth", authRouter);
51
  app.use("/moods", moodRouter);
52
  app.use("/sleep_records", sleepRecordRouter);
53
  app.use("/triggers", triggerRouter);
54

55
  app.use(errorHandler); // always last
56

57
  // TODO: flesh the actual page here
58
  app.use(express.static(path.join(__dirname, './static')));
59
  app.get(/.*/, (req, res) => {
60
    res.sendFile(path.join(__dirname, './static/index.html')); });
61

62
  process.on('SIGTERM', shutdown);
63
  process.on('SIGINT', shutdown);
64

65
  return app;
66
}
67

68
const shutdown = async () => {
69
  await Promise.all([closeAllWorkers(), closeAllQueues()]);
70
  process.exit(0);
71
};