-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
389 lines (346 loc) · 10.4 KB
/
server.js
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import express from 'express'
import cors from 'cors'
import axios from 'axios'
import pkg from 'python-shell'
import path from 'path'
import { fileURLToPath } from 'url'
import dotenv from 'dotenv'
import 'dotenv/config'
import analyticsRoutes from './src/routes/analytics.js'
import { validateSnowflakeConfig, syncData } from './src/utils/snowflake.js'
import fs from 'fs'
// Configure dotenv at the start
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
dotenv.config({ path: path.join(__dirname, '.env') })
// Set up file paths
const { PythonShell } = pkg
const app = express()
// Add CORS configuration
const corsOptions = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: false,
optionsSuccessStatus: 204,
allowedHeaders: ['Content-Type', 'Authorization', 'Accept', 'Origin', 'X-Requested-With'],
credentials: false,
exposedHeaders: ['Content-Type']
}
// Add request logging
app.use((req, res, next) => {
console.log(`\n====== Request Start ======`)
console.log(`${req.method} ${req.url}`)
console.log('Headers:', req.headers)
console.log('Query:', req.query)
console.log('Body:', req.body)
const start = Date.now()
// Capture the original res.json to add logging
const originalJson = res.json
res.json = function(data) {
console.log(`Response data:`, data)
if (data && data.error) {
console.error('Response error:', data.error)
if (data.stack) console.error('Stack:', data.stack)
}
return originalJson.apply(this, arguments)
}
res.on('finish', () => {
const duration = Date.now() - start
console.log(`\n====== Request Complete ======`)
console.log(`${req.method} ${req.url} - ${res.statusCode} (${duration}ms)`)
if (res.statusCode >= 400) {
console.error('Error response:', {
status: res.statusCode,
method: req.method,
url: req.url,
duration: duration
})
}
})
next()
})
// Apply CORS middleware
app.use(cors(corsOptions))
// Handle OPTIONS requests explicitly
app.options('*', cors(corsOptions))
// Add CORS headers to all responses
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS')
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Accept, Origin, X-Requested-With')
res.header('Content-Type', 'application/json')
next()
})
// Parse JSON bodies
app.use(express.json())
// Mount analytics routes
app.use('/api/analytics', analyticsRoutes)
// Root endpoint
app.get('/', (req, res) => {
res.json({
message: 'Crypto Tracker API',
status: 'running',
endpoints: ['/health', '/debug', '/api/prices', '/api/markets', '/api/search', '/api/analytics/*']
})
})
// Health check endpoint
app.get('/health', (req, res) => {
console.log('Health check requested')
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development',
version: '1.0.0',
snowflake: validateSnowflakeConfig()
})
})
// Debug endpoint
app.get('/debug', (req, res) => {
console.log('Debug info requested')
res.json({
status: 'ok',
headers: req.headers,
origin: req.get('origin'),
method: req.method,
path: req.path,
env: process.env.NODE_ENV || 'development',
node_version: process.version,
memory_usage: process.memoryUsage(),
uptime: process.uptime()
})
})
// Set default values for APIs
const COINGECKO_API_URL = process.env.COINGECKO_API_URL || 'https://api.coingecko.com/api/v3'
const COINGECKO_API_KEY = process.env.COINGECKO_API_KEY || 'CG-DEMO-KEY'
// Create axios instance for CoinGecko
const coingeckoApi = axios.create({
baseURL: COINGECKO_API_URL,
timeout: 10000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-cg-demo-api-key': COINGECKO_API_KEY
}
})
// Debug logging helper
const debugLog = (message, data) => {
console.log(`[DEBUG] ${message}:`, JSON.stringify(data, null, 2))
}
// Add logging interceptor
coingeckoApi.interceptors.request.use(request => {
debugLog('Making CoinGecko request', {
url: request.url,
params: request.params,
headers: {
...request.headers,
'x-cg-demo-api-key': 'HIDDEN' // Hide API key in logs
}
})
return request
})
// Price endpoint
app.get('/api/prices', async (req, res) => {
try {
const { ids } = req.query
if (!ids) {
return res.status(400).json({ error: 'Missing coin IDs' })
}
const idArray = ids.split(',')
try {
const response = await coingeckoApi.get('/coins/markets', {
params: {
vs_currency: 'usd',
ids: idArray.join(','),
order: 'market_cap_desc',
per_page: 250,
sparkline: false,
price_change_percentage: '24h'
}
})
const formattedData = {}
response.data.forEach(coin => {
formattedData[coin.id] = {
usd: coin.current_price,
usd_24h_change: coin.price_change_percentage_24h,
usd_24h_vol: coin.total_volume,
usd_market_cap: coin.market_cap
}
})
return res.json(formattedData)
} catch (coingeckoError) {
console.error('CoinGecko API error:', coingeckoError)
return res.json(idArray.reduce((acc, id) => {
acc[id] = {
usd: 0,
usd_24h_change: 0,
usd_24h_vol: 0,
usd_market_cap: 0
}
return acc
}, {}))
}
} catch (error) {
console.error('Price fetch error:', error)
res.status(500).json({
error: 'Failed to fetch prices',
details: error.message
})
}
})
// Markets endpoint
app.get('/api/markets', async (req, res) => {
try {
const response = await coingeckoApi.get('/coins/markets', {
params: {
vs_currency: 'usd',
order: 'market_cap_desc',
per_page: 10,
sparkline: false
}
})
res.json(response.data)
} catch (error) {
console.error('Markets error:', error)
res.status(500).json({
error: 'Failed to fetch markets',
details: error.message
})
}
})
// Search endpoint
app.get('/api/search', async (req, res) => {
try {
const { query } = req.query
if (!query) {
return res.status(400).json({ error: 'Missing search query' })
}
const searchResponse = await coingeckoApi.get('/search', {
params: { query }
})
if (searchResponse.data.coins.length > 0) {
const coinIds = searchResponse.data.coins.map(coin => coin.id).slice(0, 10)
const detailsResponse = await coingeckoApi.get('/coins/markets', {
params: {
vs_currency: 'usd',
ids: coinIds.join(','),
order: 'market_cap_desc',
per_page: 10,
sparkline: false,
price_change_percentage: '24h'
}
})
const enrichedResults = searchResponse.data.coins.map(coin => {
const details = detailsResponse.data.find(d => d.id === coin.id) || {}
return {
...coin,
current_price: details.current_price,
market_cap: details.market_cap,
price_change_24h: details.price_change_percentage_24h
}
})
res.json({
coins: enrichedResults.slice(0, 10)
})
} else {
res.json({ coins: [] })
}
} catch (error) {
console.error('Search error:', error)
res.status(500).json({
error: 'Failed to search',
details: error.message
})
}
})
// Snowflake sync endpoint
app.post('/api/sync-snowflake', async (req, res) => {
try {
console.log('\n=== Starting Snowflake Sync ===')
const { holdings, prices } = req.body
if (!holdings || !prices) {
console.log('❌ Missing required data')
return res.status(400).json({
error: 'Missing required data',
details: 'Both holdings and prices are required'
})
}
console.log('📊 Sync request received:', {
holdings: holdings.length,
prices: prices.length,
timestamp: new Date().toISOString()
})
// Validate Snowflake configuration
console.log('\n=== Validating Snowflake Configuration ===')
if (!validateSnowflakeConfig()) {
console.log('❌ Snowflake configuration is incomplete')
return res.status(500).json({
error: 'Server configuration error',
details: 'Snowflake configuration is incomplete'
})
}
console.log('✅ Snowflake configuration validated')
// Sync data using Node.js Snowflake driver
const result = await syncData(holdings, prices)
if (result.status === 'error') {
console.error('❌ Sync failed:', result.message)
return res.status(500).json(result)
}
console.log('✅ Sync completed successfully')
res.json(result)
} catch (error) {
console.error('\n=== Sync Error ===')
console.error('Error details:', {
message: error.message,
stack: error.stack,
timestamp: new Date().toISOString()
})
res.status(500).json({
error: 'Failed to sync with Snowflake',
details: error.message,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
})
}
})
// Error handling middleware
app.use((err, req, res, next) => {
console.error(`\n====== Error Handler ======`)
console.error('Error:', err)
console.error('Stack:', err.stack)
console.error('Request details:', {
method: req.method,
url: req.url,
headers: req.headers,
query: req.query,
body: req.body
})
// Ensure we send a JSON response
res.status(err.status || 500).json({
error: process.env.NODE_ENV === 'production' ? 'Internal Server Error' : err.message,
status: err.status || 500,
path: req.path,
stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
})
})
// 404 handler - ensure JSON response
app.use((req, res) => {
console.log(`\n====== 404 Not Found ======`)
console.log('Request details:', {
method: req.method,
url: req.url,
headers: req.headers,
query: req.query,
body: req.body
})
res.status(404).json({
error: 'Not Found',
message: `Cannot ${req.method} ${req.url}`,
path: req.path
})
})
const PORT = process.env.PORT || 3001
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on port ${PORT}`)
console.log('Environment:', process.env.NODE_ENV)
console.log('CoinGecko API URL:', COINGECKO_API_URL)
console.log('Server listening on all interfaces (0.0.0.0)')
})