Home > Enterprise >  Middleware is breaking redis / express setup
Middleware is breaking redis / express setup

Time:05-23

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!

CodePudding user response:

Your cache function

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();
        }
    });
}

uses node redis 3 "logic" so it's hanging

redis 4 is promise led, so you need to use async/await or .then/.catch

So something like this should work for the .then/.catch approach

// Cache middleware
function cache(req, res, next) {
    console.log('caching for', req.params);
    const { username } = req.params;

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

This will solve your initial problem of "why it's getting stuck"

  • Related