'Middleware is breaking redis / express setup

I'm using redis for the first time, and I can't quite figure out why my middleware 'cache' function is breaking my code? It works great without it, displays in the browser, if I go to my terminal and check for a key value pair it works great.

Here is my setup:

const express = require("express");
const redis = require("redis");
const axios = require("axios").default;

const PORT = process.env.PORT || 5000;
const REDIS_PORT = process.env.PORT || 6379;

const client = redis.createClient(REDIS_PORT);
client.connect();
const app = express();

function setResponse(username, repos) {
    return `<h2>${username} has ${repos} Github repos</h2>`;
}

// make req to github
async function getRepos(req, res, next) {
    try {
        console.log("fetching data...");
        const { username } = req.params;
        const response = await axios.get(
            `https://api.github.com/users/${username}`
        );

        const data = response.data;

        const repos = data.public_repos;

        // set to redis
        client.set(username, repos);

        res.send(setResponse(username, repos));
    } catch (err) {
        console.log(err);
        res.status(500);
    }
}

// Cache middleware
function cache(req, res, next) {
    const { username } = req.params;

    client.get(username, (err, data) => {
        if (err) throw err;
        if (data !== null) {
            res.send(setResponse(username, data));
        } else {
            next();
        }
    });
}

app.get("/repos/:username", cache, getRepos);

app.listen(5000, () => {
    console.log(`App listening on port ${PORT}`);
});

Any advice would be much appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source