Problem:
I am using ipManager as a middleware. But due to some reason the the same json object is getting added to firestore two times. Also, many other lines are getting repeated.
Code:
//imports...
exports.ipManager = (req, res, next) => {
const ip = req.clientIp;
const fullUrl = req.protocol + "://" + req.get("host") + req.originalUrl;
console.log(fullUrl)
if ((ip == "::1") & req.get("host").includes("localhost")) {
console.log(
"[+] ipManager functionalities restricted due to server running in local machine"
);
console.info(`[+] method=GET path=${fullUrl}`);
next();
return;
}
const _URL = req.originalUrl
if (_URL.includes("documentation") || _URL.includes("weather") || _URL=="/") {
console.log(_URL)
} else {
next()
return
}
console.log("IP address " + ip);
axios
.get(`http://ip-api.com/json/${ip}`)
// Show response data
.then((res) => {
const info = res.data;
console.info(JSON.stringify(res.data));
(async () => {
try {
const docRef = await addDoc(collection(db, "req_info_2022.1.22"), {
country: info.country,
countryCode: info.countryCode,
region: info.region,
regionName: info.regionName,
city: info.city,
zip: info.zip,
lat: info.lat,
lon: info.lon,
timezone: info.timezone,
isp: info.isp,
org: info.org,
as: info.as,
ip: info.query,
path: fullUrl,
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
})()
})
.catch((err) => console.log(err));
next();
};
This is the console log statements:
Note: Observe that the console.logs are getting repeated two times. Due to this, two documents(which are same) are getting saved in the firebase collection.