Skip to content

Commit 04f345d

Browse files
authored
Create edge-server.js
1 parent ce0d572 commit 04f345d

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

edge-nodes/edge-server.js

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// edge-nodes/edge-server.js
2+
3+
const express = require('express');
4+
const bodyParser = require('body-parser');
5+
const { storeData } = require('../scripts/utils/ipfsUtils');
6+
const { submitDataToOracle } = require('../scripts/offchain_processing');
7+
const rateLimit = require('express-rate-limit');
8+
const { body, validationResult } = require('express-validator');
9+
const winston = require('winston');
10+
require('dotenv').config(); // Load environment variables from .env file
11+
12+
// Initialize Express app
13+
const app = express();
14+
const PORT = process.env.PORT || 3000;
15+
16+
// Middleware
17+
app.use(bodyParser.json());
18+
19+
// Logger setup
20+
const logger = winston.createLogger({
21+
level: 'info',
22+
format: winston.format.json(),
23+
transports: [
24+
new winston.transports.Console(),
25+
new winston.transports.File({ filename: 'error.log', level: 'error' }),
26+
new winston.transports.File({ filename: 'combined.log' }),
27+
],
28+
});
29+
30+
// Rate limiting middleware
31+
const limiter = rateLimit({
32+
windowMs: 1 * 60 * 1000, // 1 minute
33+
max: 100, // Limit each IP to 100 requests per windowMs
34+
message: 'Too many requests, please try again later.',
35+
});
36+
app.use(limiter);
37+
38+
// Health check endpoint
39+
app.get('/health', (req, res) => {
40+
res.status(200).json({ status: 'UP' });
41+
});
42+
43+
// Endpoint to handle incoming data for processing
44+
app.post('/process',
45+
// Input validation
46+
body('dataType').isString().notEmpty().withMessage('Data type must be a non-empty string.'),
47+
body('data').isString().notEmpty().withMessage('Data must be a non-empty string.'),
48+
async (req, res) => {
49+
const errors = validationResult(req);
50+
if (!errors.isEmpty()) {
51+
return res.status(400).json({ errors: errors.array() });
52+
}
53+
54+
const { dataType, data } = req.body;
55+
56+
try {
57+
// Step 1: Store data on IPFS
58+
const cid = await storeData({ dataType, data });
59+
60+
// Step 2: Submit the CID to the Oracle contract
61+
await submitDataToOracle(dataType, cid);
62+
63+
// Respond with success
64+
res.status(200).json({ message: 'Data processed successfully', cid });
65+
} catch (error) {
66+
logger.error('Error processing data:', error);
67+
res.status(500).json({ error: 'Internal server error', details: error.message });
68+
}
69+
}
70+
);
71+
72+
// Start the server
73+
app.listen(PORT, () => {
74+
logger.info(`Edge server is running on http://localhost:${PORT}`);
75+
});

0 commit comments

Comments
 (0)