I built a boat visualizer using this API. After inquiring the API I am able to obtain a json response with the vessels I am interested in and write those API information into a MongoDB
database.
API request can be done every 1 minute, and that is why I used const NodeCache = require('node-cache');
module to by-pass the 1-minute limit.
The problem: Everything seems to be working well, but if I manually refresh the page to see the updated position of the vessels and send a request before 1 minute I get a 304
of Unhandled promise rejection
. So the program does not crash, but skip constantly 1 minute in writing the information to MongoDB
. Meaning that I get the position every 2 minutes because of the refresh page action instead of every 1 minute. Why is that happening?
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
Typical answer from the API is the following below:
[
{
"AIS":{
"MMSI":227441980,
"TIMESTAMP":"2017-08-11 11:17:37 UTC",
"LATITUDE":46.1459,
"LONGITUDE":-1.16631,
"COURSE":360.0,
"SPEED":0.0,
"HEADING":511,
"NAVSTAT":1,
"IMO":0,
"NAME":"CLEMENTINE",
"CALLSIGN":"FJVK",
"TYPE":60,
"A":0,
"B":0,
"C":0,
"D":0,
"DRAUGHT":0.0,
"DESTINATION":"",
"ETA_AIS":"00-00 00:00",
"ETA":"",
"SRC":"TER",
"ZONE": "North Sea",
"ECA": true
}
}
]
Below the most important part of the code:
server
var express = require('express');
var router = express.Router();
var axios = require('axios');
const NodeCache = require('node-cache');
const myCache = new NodeCache();
let hitCount = 0;
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/hello', async function(req, res, next) {
const allData = myCache.get('allData');
if (!allData) {
hitCount++;
try {
const { data } = await axios.get(
'https://api.vesselfinder.com/vesselslist?userkey=KEY'
);
const { metaData, ships } = data;
myCache.set('allData', data, 70);
console.log(data + 'This is the data');
res.send(data);
} catch (error) {
res.send(error);
console.log(error);
}
}
res.send(allData);
});
module.exports = router;
client
class BoatMap extends Component {
constructor(props) {
super(props);
this.state = {
// .........
};
this.updateRequest = this.updateRequest.bind(this);
}
async componentDidMount() {
this.countDownInterval = setInterval(() => {
}, 500);
await this.updateRequest();
this.updateInterval = setInterval(() => {
this.updateRequest();
}, 60 * 1000);
}
async updateRequest() {
const url = 'http://localhost:3001/hello';
const fetchingData = await fetch(url);
const ships = await fetchingData.json();
console.log('fetched ships', ships);
if (JSON.stringify(ships) !== '{}') {
if (this.previousTimeStamp === null) {
this.previousTimeStamp = ships.reduce(function(obj, ship) {
obj[ship.AIS.NAME] = ship.AIS.TIMESTAMP;
return obj;
}, {});
}
this.setState({
ships: ships,
filteredShips: ships
});
this.props.callbackFromParent(ships);
for (let ship of ships) {
if (this.previousTimeStamp !== null) {
if (this.previousTimeStamp[ship.AIS.NAME] === ship.AIS.TIMESTAMP) {
this.previousTimeStamp[ship.AIS.NAME] = ship.AIS.TIMESTAMP;
console.log('Same timestamp: ', ship.AIS.NAME, ship.AIS.TIMESTAMP);
continue;
} else {
this.previousTimeStamp[ship.AIS.NAME] = ship.AIS.TIMESTAMP;
}
}
let _ship = {
// ships data ....
};
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(_ship)
};
await fetch('http://localhost:3001/users/vessles/map/latlng', requestOptions);
}
}
}
}
render() {
const noHoverOnShip = this.state.hoverOnActiveShip === null;
// console.log("color", this.state.trajectoryColor);
return (
<div className="google-map">
<GoogleMapReact
// ships={this.state.ships}
bootstrapURLKeys={{ key: 'key' }}
center={{
lat: this.props.activeShip ? this.props.activeShip.latitude : 37.99,
lng: this.props.activeShip ? this.props.activeShip.longitude : -97.31
}}
zoom={5.5}
onGoogleApiLoaded={({ map, maps }) => {
this.map = map;
this.maps = maps;
// we need this setState to force the first mapcontrol render
this.setState({ mapControlShouldRender: true, mapLoaded: true });
}}
>
{this.state.mapLoaded ? (
<div>
<Polyline
map={this.map}
maps={this.maps}
markers={this.state.trajectoryData}
lineColor={this.state.trajectoryColor}
/>
</div>
) : (
''
)}
{/* Rendering all the markers here */}
{this.state.filteredShips.map((ship) => (
<Ship
ship={ship}
key={ship.AIS.MMSI}
lat={ship.AIS.LATITUDE}
lng={ship.AIS.LONGITUDE}
logoMap={this.state.logoMap}
logoClick={this.handleMarkerClick}
logoHoverOn={this.handleMarkerHoverOnShip}
logoHoverOff={this.handleMarkerHoverOffInfoWin}
/>
))}
What I have done so far:
1) I also came across this source to help me solve the problem but no luck.
2) Also I consulted this other source, and also this one but both of them did not help me to figure out what the problem might be.
3) I dug more into the problem and found this source too.
4) I read this one too. However, neither of these has helped me fix the problem.
5) I also found this source very useful but still no solution.
Thank you very much for pointing to the right direction for solving this issue.