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