Home > Software design >  Response is not being sent back when using redis client
Response is not being sent back when using redis client

Time:02-21

Why is no response being sent back in any of the cases (cache hit or miss)? I dont get any error either. I'm trying to set up a simple redis based project.

import express from "express";
import axios from "axios";
let app = express();
import logger from "morgan";
import { createClient } from "redis";

const client = createClient();
await client.connect();

app.use(express.json());
app.use(logger("dev"));

app.get("/photos", async function (req, res) {
  await client.get("photos", async (err, photos) => {
    if (err) return next(err);
    if (photos !== null) return res.json(JSON.parse(photos));

    const { data } = await axios.get(
      "https://jsonplaceholder.typicode.com/photos"
    );

    await client.setEx("photos", JSON.stringify(data));
    res.json(data);
  });
});

CodePudding user response:

The issue is that you are mixing callback functionality with the newer async/await logic. According to the npm-redis docs the way to access a keys value is with await client.get()

app.get("/photos", async function (req, res) {
  const photos = await client.get("photos");
  if (photos) {
    res.json(JSON.parse(photos))
  } else {
    try {
      const { data } = await axios.get(
        "https://jsonplaceholder.typicode.com/photos"
      );

      await client.setEx("photos", JSON.stringify(data));
      res.json(data);
    } catch(error) {
      console.error(error)
      res.json({data: error})
    }
  }
});

I have also added a try/catch block around the call to axios.get to try and capture any error that comes from the call and return that error in the response

  • Related