I am making RESTful APIs for my client to access and see some JSON data. I have three files in my project, app.js, mysql.js, and routes.js.
The app.js uses the following:
const express = require('express');
const app = express();
const PORT = process.env.PORT;
app.use(express.json());
app.use("/api", require("./routes"));
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
and the routes.js is the following:
const express = require('express');
const router = express.Router();
const connection = require('./mysql');
const moment = require('moment');
const updateRoutes = () => {
connection.query(`SELECT * FROM projects`, (err, projects) => {
if (err) {
console.error(err);
return res.status(500).json({ error: 'Internal Server Error' });
}
projects.length > 0 && projects.forEach(project => {
router.get(`/${project.api_access_token}`, async (req, res) => {
try {
res.json(project);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
});
});
});
}
updateRoutes();
setInterval(updateRoutes, 60000);
module.exports = router;
I might have missed a bracket somewhere because I just copied one of my routes but I have many.
Basically, since the data is coming from a MySQL database, I want the res.json for the API is updated every 1 minute so that when the client reloads his browser, he can see the updated data in the json without me needing to restart the app.
How to do it?
Help pls.
Thanks.