-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
241 lines (194 loc) · 6.84 KB
/
Copy pathserver.js
File metadata and controls
241 lines (194 loc) · 6.84 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
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
/**
* Merch MVP Backend Server
*
* Features:
* - Signature-based minting
* - IPFS image upload (Pinata)
* - Event listener (auto code generation)
* - Admin endpoints
*/
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const db = require('./database/db');
const { getListenerService } = require('./services/event-listener');
// ============ Configuration ============
const PORT = process.env.PORT || 3000;
const NODE_ENV = process.env.NODE_ENV || 'development';
const BASE_URL = process.env.BASE_URL || `http://localhost:${PORT}`;
const ENABLE_EVENT_LISTENER = process.env.ENABLE_EVENT_LISTENER === 'true';
const PROCESS_HISTORICAL_EVENTS = process.env.PROCESS_HISTORICAL_EVENTS === 'true';
const HISTORICAL_FROM_BLOCK = process.env.HISTORICAL_FROM_BLOCK || 'earliest';
// ============ Express App ============
const app = express();
// Trust proxy (required for Render.com and rate limiting)
app.set('trust proxy', 1);
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Rate limiting
const limiter = rateLimit({
windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000, // 15 min
max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100,
message: 'Too many requests from this IP, please try again later'
});
app.use('/api/', limiter);
// ============ Routes ============
// Health check
app.get('/health', (req, res) => {
let backendIssuer = null;
if (process.env.BACKEND_ISSUER_PRIVATE_KEY) {
try {
const { Wallet } = require('ethers');
backendIssuer = new Wallet(process.env.BACKEND_ISSUER_PRIVATE_KEY).address;
} catch (error) {
console.error('Error getting backend issuer address:', error.message);
}
}
res.json({
status: 'ok',
environment: NODE_ENV,
timestamp: new Date().toISOString(),
backendIssuer,
contractConfigured: !!process.env.MERCH_MANAGER_ADDRESS,
features: {
eventListener: ENABLE_EVENT_LISTENER,
imageUpload: !!process.env.PINATA_JWT,
dynamicEvents: true
}
});
});
// Event listener health check
app.get('/health/listener', async (req, res) => {
if (!ENABLE_EVENT_LISTENER) {
return res.json({
status: 'disabled',
message: 'Event listener is disabled in configuration'
});
}
try {
const listener = getListenerService();
const health = await listener.healthCheck();
res.json(health);
} catch (error) {
res.status(500).json({
status: 'error',
message: error.message
});
}
});
// Import route modules
const claimsRoutes = require('./routes/claims');
const eventsRoutes = require('./routes/events');
// Mount routes
app.use('/api', claimsRoutes);
app.use('/api/events', eventsRoutes);
// Codes generation routes (for Chainlink Automation)
const codesRoutes = require('./routes/codes');
app.use('/api', codesRoutes);
// Merch routes
const merchRoutes = require('./routes/merch');
app.use('/api', merchRoutes);
// Admin routes
const adminRoutes = require('./routes/admin');
app.use('/api/admin', adminRoutes);
// Metadata routes (if exists)
try {
const metadataRoutes = require('./routes/metadata');
app.use('/api', metadataRoutes);
} catch (e) {
console.log('⚠️ Metadata routes not found - skipping');
}
// Attestation routes (if exists)
try {
const attestationRoutes = require('./routes/attestations');
app.use('/api', attestationRoutes);
} catch (e) {
console.log('⚠️ Attestation routes not found - skipping');
}
// 404 handler
app.use((req, res) => {
res.status(404).json({
error: 'Endpoint not found',
path: req.path,
method: req.method
});
});
// Error handler
app.use((err, req, res, next) => {
console.error('❌ Server error:', err);
res.status(500).json({
error: 'Internal server error',
message: NODE_ENV === 'development' ? err.message : 'Something went wrong'
});
});
// ============ Startup ============
async function startServer() {
try {
console.log('\n🚀 Starting Merch MVP Backend...\n');
// Initialize database
await db.initializeDatabase();
// Initialize event listener (if enabled)
if (ENABLE_EVENT_LISTENER) {
console.log('🎧 Initializing Event Listener Service...');
const listener = getListenerService();
await listener.initialize();
// Process historical events (if enabled)
if (PROCESS_HISTORICAL_EVENTS) {
await listener.processHistoricalEvents(HISTORICAL_FROM_BLOCK);
}
// Start listening for new events
await listener.startListening();
console.log('════════════════════════════════════════');
console.log('🎉 BACKEND LISTO PARA RECIBIR EVENTOS');
console.log('════════════════════════════════════════\n');
} else {
console.log('⚠️ Event Listener is disabled\n');
}
// Start HTTP server
app.listen(PORT, () => {
console.log('✅ Server running on port', PORT);
console.log('📍 Base URL:', BASE_URL);
console.log('🌐 Environment:', NODE_ENV);
console.log('\n════════════════════════════════════════');
console.log('📋 Available Endpoints:');
console.log('════════════════════════════════════════');
console.log('GET /health');
console.log('GET /health/listener');
console.log('POST /api/verify-code');
console.log('POST /api/events/upload-image');
console.log('GET /api/events/image/:hash');
console.log('GET /api/admin/stats');
console.log('GET /api/admin/list-claims');
console.log('GET /api/admin/events-summary');
console.log('════════════════════════════════════════\n');
});
} catch (error) {
console.error('❌ Failed to start server:', error);
process.exit(1);
}
}
// ============ Graceful Shutdown ============
process.on('SIGTERM', async () => {
console.log('\n🛑 SIGTERM received, shutting down gracefully...');
if (ENABLE_EVENT_LISTENER) {
const listener = getListenerService();
listener.stopListening();
}
await db.closePool();
process.exit(0);
});
process.on('SIGINT', async () => {
console.log('\n🛑 SIGINT received, shutting down gracefully...');
if (ENABLE_EVENT_LISTENER) {
const listener = getListenerService();
listener.stopListening();
}
await db.closePool();
process.exit(0);
});
// ============ Start ============
startServer();
module.exports = app;