-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
49 lines (41 loc) · 1.39 KB
/
Copy pathserver.ts
File metadata and controls
49 lines (41 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import express, { Express, Request, Response, NextFunction } from 'express'
import dotenv from 'dotenv'
import { generateToken } from './auth'
import { connectDatabases } from './database'
dotenv.config()
const app: Express = express()
const PORT = process.env.PORT || 5001
app.use(express.json())
// Define a health check endpoint
app.get('/health', (req: Request, res: Response) => {
res.json({ status: 'Server is running' })
})
app.post('/login', async (req: Request, res: Response, next: NextFunction) => {
const { username, password } = req.body
try {
const token = await generateToken(username)
res.json({ token })
} catch (error) {
res.status(401).json({ message: 'Invalid credentials' })
next(error)
}
})
const startServer = async () => {
try {
const { pgPool, mongoose } = await connectDatabases()
console.log('🚀 Databases connected, starting server...')
// Store database connections for use in routes
app.locals.pgPool = pgPool
app.locals.mongoose = mongoose
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`)
})
} catch (error) {
console.error(
'❌ Failed to connect to databases. Server not started.',
error
)
process.exit(1) // Exit process if database connection fails
}
}
startServer()