This is the code for a basic endpoint in my express app routes folder. This firstly renders a page, and then on a continuous loop, renders information about some random "Breaking Bad" character.
The idea is to have the page load, and then every two seconds, the page updates automatically with the new character info. Then two seconds later, a new character replaces the one on the screen, and so on.
To do this, I'm making use of a convenient Breaking Bad REST-ful API
const express = require("express");
const app = require("../app");
const router = express.Router();
const axios = require("axios");
const socket = require("../socketioAPI");
router.get("/", function(req, res, next) {
runCharacterUpdateInterval();
res.render("index", { title: "Breaking Bad Page" });
});
const runCharacterUpdateInterval = () => {
const updateTime = 2000;
setInterval(() => {
updatePageWithRandomCharacter();
}, updateTime);
};
const updatePageWithRandomCharacter = () => {
createCharacter().then(profile => {
socket.push("breaking bad", profile);
});
};
const createCharacter = async () => {
const characterId = getRandomCharacterId();
const bio = await queryAPI("characters/" + characterId);
const { quote } = await queryAPI("quote/random?author=" + encode(bio.name));
const { deathCount } = await queryAPI("death-count?name=" + encode(bio.name));
return await { bio, quote, deathCount };
};
const encode = name => {
return name.replace(/ /g, "+");
};
const getRandomCharacterId = () => {
const totalChar = 54;
const initalChar = 1;
return Math.floor(Math.random() * Math.floor(totalChar)) + initalChar;
};
const queryAPI = async endpoint => {
const api = await axios.get(`https://www.breakingbadapi.com/api/${endpoint}`);
if (await api.data[0]) return await api.data[0];
else return { name: [], quote: [], deathCount: [] };
};
module.exports = router;
In the past, my code has been reviewed as "spaghetti-like", and not clean. I've been trying to fix this, and so any pointers on the style, readability, or anything code related would be greatly appreciated.