-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
216 lines (189 loc) Β· 8.05 KB
/
index.ts
File metadata and controls
216 lines (189 loc) Β· 8.05 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import express, { json, urlencoded, raw } from 'express'
import { UserController } from './controllers/UserController'
import { GeoLocationController } from './controllers/GeoLocationController'
import { FriendsController } from './controllers/FriendsController'
import { RollupController } from './controllers/RollupController'
import { MarketingController } from './controllers/MarketingController'
import { JobQueueController } from './controllers/JobQueueController'
import { SlackController } from './controllers/SlackController'
import { NotificationTestController } from './controllers/NotificationTestController'
import { CheckoutController } from './controllers/CheckoutController'
import { LicenseController } from './controllers/LicenseController'
import { WebhookController } from './controllers/WebhookController'
import { GeoLocationService } from './services/GeoLocationService'
import { jobQueueService } from './services/JobQueueService'
import { slackCleanupQueueService } from './services/SlackCleanupQueueService'
import { ApiError } from './middleware/errorHandler'
const app = express()
const PORT = parseInt(process.env.PORT || '8001', 10)
// Webhook middleware (needs raw body for signature verification)
app.use('/api/webhooks/stripe', raw({ type: 'application/json' }))
// Middleware
app.use(json())
app.use(urlencoded({ extended: true }))
// CORS middleware (basic setup)
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
if (req.method === 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
})
// Health check endpoint (no auth required)
app.get('/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
service: 'Ebb Platform API'
})
})
// API Routes (protected by authentication middleware)
app.use('/api/users', UserController.router)
app.use('/api/geolocation', GeoLocationController.router)
app.use('/api/friends', FriendsController.router)
app.use('/api/rollup', RollupController.router)
app.use('/api/jobs', JobQueueController.router)
app.use('/api/slack', SlackController.router)
app.use('/api/notifications', NotificationTestController.router)
app.use('/api/checkout', CheckoutController.router)
app.use('/api/license', LicenseController.router)
// Public API Routes (no authentication required)
app.use('/api/marketing', MarketingController.router)
app.use('/api/webhooks', WebhookController.router)
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({
success: false,
error: 'Route not found'
})
})
// Error handler - Fixed signature with next parameter
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
// Don't log expected authentication errors during tests
const isTestMode = process.env.NODE_ENV === 'test'
const isAuthError = err instanceof ApiError && [401, 403].includes(err.statusCode)
if (!isTestMode || !isAuthError) {
console.error('Unhandled error:', {
message: err.message,
stack: err.stack,
url: req.url,
method: req.method,
timestamp: new Date().toISOString()
})
}
// Handle custom API errors
if (err instanceof ApiError) {
const isDevelopment = process.env.NODE_ENV === 'development'
res.status(err.statusCode).json({
success: false,
error: err.message,
...(isDevelopment && { details: err.message, stack: err.stack })
})
return
}
// Handle other errors
const isDevelopment = process.env.NODE_ENV === 'development'
res.status(500).json({
success: false,
error: 'Internal server error',
...(isDevelopment && { details: err.message, stack: err.stack })
})
})
// Global error handlers to prevent server crashes
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', {
message: error.message,
stack: error.stack,
timestamp: new Date().toISOString()
})
// In production, we might want to restart the process
// For now, we'll just log and continue
if (process.env.NODE_ENV === 'production') {
console.error('Server encountered an uncaught exception but will continue running')
}
})
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason)
console.error('Timestamp:', new Date().toISOString())
})
// Graceful shutdown handlers
process.on('SIGTERM', async () => {
console.log('π SIGTERM received, shutting down gracefully...')
await gracefulShutdown()
})
process.on('SIGINT', async () => {
console.log('π SIGINT received, shutting down gracefully...')
await gracefulShutdown()
})
async function gracefulShutdown() {
try {
await Promise.all([
jobQueueService.shutdown(),
slackCleanupQueueService.shutdown()
])
console.log('β
Graceful shutdown completed')
process.exit(0)
} catch (error) {
console.error('β Error during graceful shutdown:', error)
process.exit(1)
}
}
// Function to start the server
export const startServer = async (port: number = PORT) => {
try {
// Initialize services
console.log('π§ Initializing services...')
// Initialize GeoLocationService (will fail gracefully if database not found)
try {
await GeoLocationService.initialize()
} catch (error) {
console.warn('β οΈ GeoLocationService initialization failed:', error)
console.warn(' Geolocation features will not be available.')
console.warn(' To enable geolocation, set GEOIP_DATABASE_PATH environment variable.')
}
// Initialize Job Queue Service (will fail gracefully if Redis not available)
try {
await jobQueueService.initialize()
} catch (error) {
console.warn('β οΈ Job Queue Service initialization failed:', error)
console.warn(' Scheduled user monitoring jobs will not be available.')
console.warn(' To enable job queue, ensure Redis is running and properly configured.')
}
// Initialize Slack Cleanup Queue Service (will fail gracefully if Redis not available)
try {
await slackCleanupQueueService.initialize()
} catch (error) {
console.warn('β οΈ Slack Cleanup Queue Service initialization failed:', error)
console.warn(' Slack focus session cleanup jobs will not be available.')
console.warn(' To enable Slack cleanup, ensure Redis is running and properly configured.')
}
console.log('β
Services initialized successfully')
return app.listen(port, () => {
console.log(`π Server running on port ${port}`)
console.log(`π Health check: http://localhost:${port}/health`)
console.log(`π₯ Users API (auth required): http://localhost:${port}/api/users`)
console.log(`π Geolocation API (auth required): http://localhost:${port}/api/geolocation`)
console.log(`π Friends API (auth required): http://localhost:${port}/api/friends`)
console.log(`π Rollup API (auth required): http://localhost:${port}/api/rollup`)
console.log(`π Marketing API (public): http://localhost:${port}/api/marketing`)
console.log(`βοΈ Job Queue API (auth required): http://localhost:${port}/api/jobs`)
console.log(`π¬ Slack API (auth required): http://localhost:${port}/api/slack`)
console.log(`π³ Checkout API (auth required): http://localhost:${port}/api/checkout`)
console.log(`π« License API (auth required): http://localhost:${port}/api/license`)
console.log(`π Webhooks API (public): http://localhost:${port}/api/webhooks`)
console.log(`βοΈ Job Queue: User monitoring jobs scheduled (requires Redis)`)
console.log('π Authentication: Supabase JWT required for /api routes (except marketing, webhooks, and slack/events)')
})
} catch (error) {
console.error('β Failed to start server:', error)
process.exit(1)
}
}
// Auto-start server only when this file is run directly
if (import.meta.main) {
startServer()
}
export default app