diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..e9c1dc0 --- /dev/null +++ b/src/index.ts @@ -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); \ No newline at end of file diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..5310ca7 --- /dev/null +++ b/src/server.ts @@ -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; \ No newline at end of file diff --git a/src/utils/portCheck.ts b/src/utils/portCheck.ts new file mode 100644 index 0000000..fad3cef --- /dev/null +++ b/src/utils/portCheck.ts @@ -0,0 +1,18 @@ +import net from 'net'; + +export function isPortAvailable(port: number | string): Promise { + return new Promise((resolve) => { + const server = net.createServer(); + + server.once('error', () => { + resolve(false); + }); + + server.once('listening', () => { + server.close(); + resolve(true); + }); + + server.listen(port); + }); +} \ No newline at end of file