82 lines
1.8 KiB
TypeScript
Executable File
82 lines
1.8 KiB
TypeScript
Executable File
/**
|
|
* This is a API server
|
|
*/
|
|
|
|
import express, { type Request, type Response, type NextFunction } from 'express';
|
|
import cors from 'cors';
|
|
import path from 'path';
|
|
import dotenv from 'dotenv';
|
|
import { fileURLToPath } from 'url';
|
|
import authRoutes from './routes/auth.js';
|
|
import videoRoutes from './routes/videos.js';
|
|
import statsRoutes from './routes/stats.js';
|
|
import uploadRoutes from './routes/upload.js';
|
|
import topicsRoutes from './routes/topics.js';
|
|
import categoriesRoutes from './routes/categories.js';
|
|
import { initDatabase } from './config/database.js';
|
|
|
|
// for esm mode
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
// load env
|
|
dotenv.config();
|
|
|
|
|
|
const app: express.Application = express();
|
|
|
|
app.use(cors());
|
|
app.use(express.json({ limit: '10mb' }));
|
|
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
|
|
|
|
/**
|
|
* Initialize Database
|
|
*/
|
|
initDatabase().catch(console.error);
|
|
|
|
/**
|
|
* API Routes
|
|
*/
|
|
app.use('/api/auth', authRoutes);
|
|
app.use('/api/videos', videoRoutes);
|
|
app.use('/api/stats', statsRoutes);
|
|
app.use('/api/upload', uploadRoutes);
|
|
app.use('/api/topics', topicsRoutes);
|
|
app.use('/api/categories', categoriesRoutes);
|
|
|
|
/**
|
|
* Static file serving for uploads
|
|
*/
|
|
app.use('/uploads', express.static(path.join(process.cwd(), 'uploads')));
|
|
|
|
/**
|
|
* health
|
|
*/
|
|
app.use('/api/health', (req: Request, res: Response, next: NextFunction): void => {
|
|
res.status(200).json({
|
|
success: true,
|
|
message: 'ok'
|
|
});
|
|
});
|
|
|
|
/**
|
|
* error handler middleware
|
|
*/
|
|
app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
|
|
res.status(500).json({
|
|
success: false,
|
|
error: 'Server internal error'
|
|
});
|
|
});
|
|
|
|
/**
|
|
* 404 handler
|
|
*/
|
|
app.use((req: Request, res: Response) => {
|
|
res.status(404).json({
|
|
success: false,
|
|
error: 'API not found'
|
|
});
|
|
});
|
|
|
|
export default app; |