Add package.json and index.js files
This commit is contained in:
95
index.js
Normal file
95
index.js
Normal file
@@ -0,0 +1,95 @@
|
||||
const express = require('express');
|
||||
const axios = require('axios');
|
||||
const app = express();
|
||||
const port = 7000;
|
||||
|
||||
app.use(express.json());
|
||||
|
||||
const RETRY_ERROR_CODES = [408, 500, 502, 503, 504, 522, 524, 599];
|
||||
|
||||
async function main() {
|
||||
|
||||
const responses = [];
|
||||
|
||||
app.get('/', (req, res) => {
|
||||
res.send('Hello World!');
|
||||
});
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(`Example app listening at http://localhost:${port}`);
|
||||
});
|
||||
|
||||
async function RegisterResponse(instanceId, response) {
|
||||
if (!responses[instanceId]) {
|
||||
responses[instanceId] = []
|
||||
}
|
||||
responses[instanceId].push({
|
||||
id: response.id,
|
||||
data: response.data
|
||||
})
|
||||
console.log(`Response registered for instance ${instanceId}`);
|
||||
}
|
||||
|
||||
async function DoRequest(instanceId, requestObj) {
|
||||
const requestParams = requestObj.request || {};
|
||||
const method = requestParams.Method?.toLowerCase() || 'get';
|
||||
const url = requestParams.Url || '';
|
||||
const body = requestParams.Body || '';
|
||||
|
||||
let headers = requestParams.Headers || null;
|
||||
// if headers is a an array or is an empty object, convert it to null
|
||||
if (Array.isArray(headers) || Object.keys(headers).length === 0) {
|
||||
headers = null;
|
||||
}
|
||||
|
||||
const shouldHaveBody = ['post', 'put', 'patch'].includes(method);
|
||||
|
||||
console.log(instanceId,requestObj)
|
||||
|
||||
try {
|
||||
const response = await axios({
|
||||
method: method,
|
||||
url: url,
|
||||
headers: headers,
|
||||
data: shouldHaveBody ? body : null
|
||||
});
|
||||
|
||||
RegisterResponse(instanceId, {
|
||||
id: requestObj.id,
|
||||
data: response.data
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
app.post('/:instanceId', async (req, res) => {
|
||||
const instanceId = req.params.instanceId;
|
||||
//console.log(`Instance ID: ${instanceId}`);
|
||||
const body = req.body;
|
||||
const requests = body.requests || [];
|
||||
const waiting = body.waiting || []
|
||||
//console.log(body);
|
||||
|
||||
requests.forEach(requestObj => {
|
||||
DoRequest(instanceId,requestObj);
|
||||
});
|
||||
|
||||
const toSend = [];
|
||||
const instanceResponses = responses[instanceId] || [];
|
||||
//console.log(instanceResponses,waiting);
|
||||
instanceResponses.forEach(respObj => {
|
||||
if (waiting.includes(respObj.id)) {
|
||||
toSend.push(respObj);
|
||||
console.log(`Response sent for instance ${instanceId}`);
|
||||
}
|
||||
});
|
||||
|
||||
res.send({
|
||||
responses: toSend
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in New Issue
Block a user