|
import express, { Request, Response, NextFunction } from 'express'; |
|
import path from 'path'; |
|
import { fileURLToPath } from 'url'; |
|
import { dirname } from 'path'; |
|
import fs from 'fs'; |
|
import { auth } from './auth.js'; |
|
import { initializeDefaultUser } from '../models/User.js'; |
|
import config from '../config/index.js'; |
|
|
|
|
|
const __filename = fileURLToPath(import.meta.url); |
|
const __dirname = dirname(__filename); |
|
|
|
|
|
const findFrontendPath = (): string => { |
|
|
|
const devPath = path.join(dirname(__dirname), 'frontend', 'dist', 'index.html'); |
|
if (fs.existsSync(devPath)) { |
|
return path.join(dirname(__dirname), 'frontend', 'dist'); |
|
} |
|
|
|
|
|
const npmPath = path.join(dirname(dirname(__dirname)), 'frontend', 'dist', 'index.html'); |
|
if (fs.existsSync(npmPath)) { |
|
return path.join(dirname(dirname(__dirname)), 'frontend', 'dist'); |
|
} |
|
|
|
|
|
console.warn('Warning: Could not locate frontend files. Using default path.'); |
|
return path.join(dirname(__dirname), 'frontend', 'dist'); |
|
}; |
|
|
|
const frontendPath = findFrontendPath(); |
|
|
|
export const errorHandler = ( |
|
err: Error, |
|
_req: Request, |
|
res: Response, |
|
_next: NextFunction, |
|
): void => { |
|
console.error('Unhandled error:', err); |
|
res.status(500).json({ |
|
success: false, |
|
message: 'Internal server error', |
|
}); |
|
}; |
|
|
|
export const initMiddlewares = (app: express.Application): void => { |
|
|
|
|
|
|
|
app.use((req, res, next) => { |
|
const basePath = config.basePath; |
|
|
|
if ( |
|
req.path !== `${basePath}/sse` && |
|
!req.path.startsWith(`${basePath}/sse/`) && |
|
req.path !== `${basePath}/messages` |
|
) { |
|
express.json()(req, res, next); |
|
} else { |
|
next(); |
|
} |
|
}); |
|
|
|
|
|
initializeDefaultUser().catch((err) => { |
|
console.error('Error initializing default user:', err); |
|
}); |
|
|
|
|
|
app.use(`${config.basePath}/api`, (req, res, next) => { |
|
|
|
if (req.path === '/auth/login' || req.path === '/auth/register') { |
|
next(); |
|
} else { |
|
auth(req, res, next); |
|
} |
|
}); |
|
|
|
app.use(errorHandler); |
|
}; |
|
|