| 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 sleepRecordRouter from '@app/routes/sleepRecords';
|
| 10 | import { errorHandler } from '@app/middleware/errorHandler';
|
| 11 | import { PrismaClient } from '@prisma/client';
|
| 12 | import { bootWorkers, closeAllWorkers, closeAllQueues } from '@app/lib/queue';
|
| 13 | import pino from 'pino';
|
| 14 | import pinoHttp from 'pino-http';
|
| 15 | import path from 'path';
|
| 16 |
|
| 17 | export function createApp() {
|
| 18 | const app = express();
|
| 19 | bootWorkers();
|
| 20 |
|
| 21 | // Configure CORS
|
| 22 | app.use(cors({
|
| 23 | origin: process.env.FRONTEND_URL || '*',
|
| 24 | credentials: true
|
| 25 | }));
|
| 26 |
|
| 27 | app.use(bodyParser.json());
|
| 28 |
|
| 29 | // Create Pino logger
|
| 30 | const logger = pino({
|
| 31 | level: process.env.LOG_LEVEL || 'info',
|
| 32 | transport: {
|
| 33 | target: 'pino-pretty', // Human-readable in development
|
| 34 | options: {
|
| 35 | colorize: true,
|
| 36 | singleLine: false,
|
| 37 | messageFormat: '{if levelLabel}{levelLabel} - {end}{msg}',
|
| 38 | },
|
| 39 | },
|
| 40 | });
|
| 41 |
|
| 42 | // Use pino-http for HTTP logging (better than Morgan for structured logs)
|
| 43 | app.use(pinoHttp({ logger }));
|
| 44 |
|
| 45 | app.use("/users", userRouter);
|
| 46 | app.use("/auth", authRouter);
|
| 47 | app.use("/moods", moodRouter);
|
| 48 | app.use("/sleep_records", sleepRecordRouter);
|
| 49 |
|
| 50 | app.use(errorHandler); // always last
|
| 51 |
|
| 52 | // TODO: flesh the actual page here
|
| 53 | app.use(express.static(path.join(__dirname, './static')));
|
| 54 | app.get(/.*/, (req, res) => {
|
| 55 | res.sendFile(path.join(__dirname, './static/index.html')); });
|
| 56 |
|
| 57 | process.on('SIGTERM', shutdown);
|
| 58 | process.on('SIGINT', shutdown);
|
| 59 |
|
| 60 | return app;
|
| 61 | }
|
| 62 |
|
| 63 | const shutdown = async () => {
|
| 64 | await Promise.all([closeAllWorkers(), closeAllQueues()]);
|
| 65 | process.exit(0);
|
| 66 | };
|