simulation_engine/index.js

186 lines
5.2 KiB
JavaScript

const express = require('express');
const multer = require('multer');
const { exec } = require('child_process');
const path = require('path');
const {checkKeyMatch,checkFileMatch} = require("./lib/validation")
const bodyParser = require('body-parser');
const http = require('http');
const fs = require('fs');
const app = express();
const port = 3000;
let server;
let jsonPath="../apiSemulator/api_node_js_mongoDB/download/routes.json"
app.use(bodyParser.json());
// Multer configuration
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
});
const upload = multer({ storage: storage });
// Function to handle dynamic endpoint creation
function createEndpoint(path1, method, body, success, headers) {
//console.log(method)
//console.log(body)
// console.log(success)
// console.log(error)
let uploadFiles =body.filter(e=>e.itemType=="File");
if(uploadFiles.length>0){
console.log(method+" "+path1 +"<- FILE UPLOAD")
let fieldName =uploadFiles[0].itemName
console.log(fieldName)
app[method.toLowerCase()](path1, upload.single(fieldName), (req, res) => {
try{
let errors =checkKeyMatch(headers,req.headers,"Headers");
let onlyHeaders = body.filter(e=>e.itemType=="Header");
let headersError =checkKeyMatch(onlyHeaders,req.headers,"Headers")
errors = [...errors,...headersError];
let FileError = checkFileMatch(uploadFiles[0].fileTypes, req.file);
errors = [...errors,...FileError];
if (errors.length==0) {
res.status(200).json( parseJSON(success));
} else {
res.status(500).json({ message: errors });
}
}catch(err){
res.status(500).json({ message: err.MulterError });
}
})
}else{
console.log(method+" "+path1 )
app[method.toLowerCase()](path1, (req, res) => {
const params = extractParamsFromPath(path,req);
let errors =checkKeyMatch(headers,req.headers,"Headers");
let onlyHeaders = body.filter(e=>e.itemType=="Header");
let headersError =checkKeyMatch(onlyHeaders,req.headers,"Headers");
errors = [...errors,...headersError];
let onlyBody = body.filter(e=>e.itemType=="Body");
let onlyQuary = body.filter(e=>e.itemType=="QueryString");
let BodyError =checkKeyMatch(onlyBody,req.body);
// console.log(BodyError)
errors = [...errors,...BodyError];
let QueryError =checkKeyMatch(onlyQuary,req.query,"QueryString");
errors = [...errors,...QueryError];
//console.log(QueryError)
if (errors.length==0) {
res.status(200).json( parseJSON(success));
} else {
res.status(500).json({ message: errors });
}
});
}
}
function parseJSON(jsonString) {
try {
return JSON.parse(jsonString)
}catch(e){
return jsonString;
}
}
// Function to create endpoints dynamically based on JSON data
function createEndpointsFromJson(jsonData) {
jsonData.forEach(endpointData => {
const { path, method, exItems, success,headers } = endpointData;
createEndpoint(path, method, exItems, success, headers);
});
}
// Function to read JSON data from file and refresh routes
function refreshRoutesFromFile(filePath) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading JSON file: ${err}`);
return;
}
try {
const jsonData = JSON.parse(data);
createEndpointsFromJson(jsonData);
console.log('Routes refreshed from JSON file.');
} catch (error) {
console.error(`Error parsing JSON: ${error}`);
}
});
}
startServer(port);
function startServer(port) {
// Close the existing server if it's running
if (server) {
console.log('Closing .. . ......');
server.close();
}
refreshRoutesFromFile(jsonPath);
// Create a new server instance
server = http.createServer(app);
// Start the new server instance
console.log('Starting .. . ......');
server.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
}
fs.watch(jsonPath, (event, filename) => {
if (event === 'change') {
console.log('Endpoints file changed. Restarting server...');
exec('pm2 restart engine', (error, stdout, stderr) => {
if (error) {
console.error(`Error restarting application: ${error}`);
return;
}
console.log(`Application restarted: ${stdout}`);
startServer(port);
});
}
});
function extractParamsFromPath(path,req) {
const params = {};
const regex = /:(\w+)/g;
let match;
while ((match = regex.exec(path)) !== null) {
//console.log(match)
// match[1] contains the parameter name without the colon
params[match[1]] = req.params[match[1]]; // Initialize value, if needed
}
return params;
}