Я создаю Restful API с NodeJS и express. После того, как запрос был сделан, само приложение также выполняет запрос к некоторым другим api и обновляет базу данных.
Вначале я думал, что все работает нормально, пока я не начал тестировать его с двумя устройствами, запустив HTTP-запрос Post в одно и то же время.
Из журналов консоли я узнал, что запросы перепутались, и приложение вылетело.
Я где-то читал, что неправильное объявление глобальных переменных могло вызвать проблему или не асинхронизировать / ожидать в правильный путь.
Может ли кто-нибудь указать мне в правильном направлении, где я могу решить эту проблему.
Заранее спасибо.
Вот мой код:
require('console-stamp')(console, '[HH:MM:ss.l]');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const PORT = process.env.PORT || 5000;
const activeParkings = require('./modules/db-methods');
const api = require('./modules/message-api');
const parseMessage = require('./modules/parse-message');
const contentType = {'Content-Type': 'text/xml'};
const moment = require('moment');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/url', async (req, response) => {
// Gets timestamp of current date (formatted)
// Gets data from incoming message
var dateTimeNow = new Date().toISOString().replace("Z", "").substr(0, 19);
var phoneNumber = req.body.From.replace("whatsapp", "").replace(" ", "").replace("+", "").replace(":", "");
var messageBody = req.body.Body;
var messageSID = req.body.MessageSid;
// Validates and parses message
var parsedMessage = parseMessage.parseMessage(messageBody);
console.log("Message: " + parsedMessage);
// Initialize Twilio Response
const twiml = new MessagingResponse();
// Gets parking entry from database based on phone number
await activeParkings.getParkingByNumber(phoneNumber, async function(dbResponse) {
console.log("Checking if sender has an active or pending parking");
// If there is 1 entry in the database containing a pending or active parking action by phone number
if(dbResponse.rowCount == 1) {
// If the parking actino made by this phone number is pending (waiting on confirmation for daycard)
if(dbResponse.rows[0].pending == true) {
console.log("User has pending parking (fixed day rate)");
if(parsedMessage == "y") {
console.log("Going to start parking with fixed day rate");
await api.startParking(dbResponse.rows[0].vrn, dbResponse.rows[0].zone, async function (parkInfo, requestStatus) {
console.log("Parking started");
var parkid = parkInfo.id;
var maxDateTime = parkInfo.mdt.toString();
var startDateTime = parkInfo.sdt.toString();
var formatMaxDateTime = moment(maxDateTime).format('DD/MM/YYYY hh:mm:ss');
console.log("Park ID: " + parkid);
console.log("Start: " + startDateTime);
console.log("Max End: " + maxDateTime);
console.log("Going to confirm parking in database");
await activeParkings.confirmParking(parkid, startDateTime, maxDateTime, function(res) {
console.log("Parking updated in database");
// if parking action is succesfully started
twiml.message("message");
response.writeHead(200, contentType);
response.end(twiml.toString());
});
});
} else if (parsedMessage == "n") {
// remove from table
twiml.message("message");
response.writeHead(200, contentType);
response.end(twiml.toString());
} else {
// hier is t fout
}
} else {
// if pending is false
if(parsedMessage == "q") {
await api.stopParking(dbResponse.rows[0].parkid, async function(resp, httpStatus) {
console.log(resp);
console.log(httpStatus);
activeParkings.removeParking(dbResponse.rows[0].parkid, function(resp2) {
// if parking action initiated by this number is succesfully stopped
twiml.message("message");
response.writeHead(200, contentType);
response.end(twiml.toString());
})
});
} else {
// if parking action is started but a weird message is sent
twiml.message("message");
response.writeHead(200, contentType);
response.end(twiml.toString());
}
}
} else {
if(parsedMessage != false && parsedMessage.length == 2) {
console.log("Message is in format of start parking message");
var vrn = parsedMessage[1];
var zone = parsedMessage[0];
console.log("Retrieving zone info...");
await api.zoneInfo(zone, async function(zoneInfo, httpStatus){
console.log("Zone: " + zoneInfo);
if(zoneInfo.grant == 1) {
console.log("Fixed day rate applied to zone");
// Hier is dagkaart actief
// sla op in pending
// stuur bericht terug wachten op ja/nee
console.log("Going to insert pending parking in database");
await activeParkings.insertParking("nan", phoneNumber, "userid", dateTimeNow, "null", zone, vrn, true, function(res) {
console.log("Database succesfully updated");
twiml.message("message");
response.writeHead(200, contentType);
response.end(twiml.toString());
});
} else {
console.log("Going to start parking");
await api.startParking(vrn, zone, function (parkInfo, requestStatus) {
var parkid = parkInfo.id;
var maxDateTime = parkInfo.mdt.toString();
var startDateTime = parkInfo.sdt.toString();
var formatMaxDateTime = moment(maxDateTime).format('DD/MM/YYYY hh:mm:ss');
console.log("Parking succesfully started");
console.log("Going to insert parking in database");
activeParkings.insertParking(parkid, phoneNumber, "userid", startDateTime, maxDateTime, zone, vrn, false, function(res) {
console.log("Database succesfully updated");
// if parking action is succesfully started
twiml.message("message");
response.writeHead(200, contentType);
response.end(twiml.toString());
});
});
}
});
} else if(parsedMessage == "q") {
twiml.message("message");
response.writeHead(200, contentType);
response.end(twiml.toString());
} else {
twiml.message("message");
response.writeHead(200, contentType);
response.end(twiml.toString());
}
}
});
}).listen(PORT, () => console.log(`Listening on ${ PORT }`));