refactor: improve server initialization and port handling
- Separate server setup from initialization\n- Add port availability check utility\n- Fix double server start issue\n- Improve error handling for port conflicts
This commit is contained in:
parent
ce97671da3
commit
2ac1cb3943
3 changed files with 63 additions and 0 deletions
24
src/index.ts
Normal file
24
src/index.ts
Normal file
|
@ -0,0 +1,24 @@
|
|||
import './config/env'; // Load environment variables first
|
||||
import { startServer } from './server';
|
||||
import { isPortAvailable } from './utils/portCheck';
|
||||
import { testConnection } from './lib/supabase';
|
||||
|
||||
const PORT = process.env.PORT || 3001;
|
||||
|
||||
const init = async () => {
|
||||
if (!await isPortAvailable(PORT)) {
|
||||
console.error(`Port ${PORT} is in use. Please try a different port or free up the current one.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Test Supabase connection
|
||||
const isConnected = await testConnection();
|
||||
if (!isConnected) {
|
||||
console.error('Failed to connect to Supabase. Please check your configuration.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
startServer();
|
||||
};
|
||||
|
||||
init().catch(console.error);
|
21
src/server.ts
Normal file
21
src/server.ts
Normal file
|
@ -0,0 +1,21 @@
|
|||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import { env } from './config/env';
|
||||
import app from './app';
|
||||
import { HealthCheckService } from './lib/services/healthCheck';
|
||||
|
||||
const port = env.PORT || 3000;
|
||||
|
||||
// Health check endpoint
|
||||
app.get('/health', async (req, res) => {
|
||||
const health = await HealthCheckService.checkHealth();
|
||||
res.json(health);
|
||||
});
|
||||
|
||||
export function startServer() {
|
||||
return app.listen(port, () => {
|
||||
console.log(`Server is running on port ${port}`);
|
||||
});
|
||||
}
|
||||
|
||||
export default app;
|
18
src/utils/portCheck.ts
Normal file
18
src/utils/portCheck.ts
Normal file
|
@ -0,0 +1,18 @@
|
|||
import net from 'net';
|
||||
|
||||
export function isPortAvailable(port: number | string): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
|
||||
server.once('error', () => {
|
||||
resolve(false);
|
||||
});
|
||||
|
||||
server.once('listening', () => {
|
||||
server.close();
|
||||
resolve(true);
|
||||
});
|
||||
|
||||
server.listen(port);
|
||||
});
|
||||
}
|
Loading…
Add table
Reference in a new issue