Skip to content

Instantly share code, notes, and snippets.

@willie-hung
Last active August 1, 2023 01:49
Show Gist options
  • Save willie-hung/690bdb944ce9fd8c29d8f26e88db3d72 to your computer and use it in GitHub Desktop.
Save willie-hung/690bdb944ce9fd8c29d8f26e88db3d72 to your computer and use it in GitHub Desktop.
post_30
import express, { Request, Response } from "express";
import axios from "axios";
const app = express();
// Create Redis Client
import { createClient } from "redis";
const client = createClient();
client.on("error", (err) => console.log("Redis Client Error", err));
const connect = async () => {
try {
await client.connect();
console.log("Connected to Redis");
} catch (error) {
console.log("Error connecting to Redis", error);
}
};
connect();
app.get("/", (req: Request, res: Response) => {
res.send("I love Redis!");
});
const DEFAULT_EXPIRATION = 3600;
app.get("/photos", async (req: Request, res: Response) => {
const albumId = req.query.albumId;
// Check the cache
const value = await client.get("photos");
if (value) {
console.log("Cache hit!");
res.json(JSON.parse(value));
} else {
console.log("Cache miss!");
const data = await axios.get(
"https://jsonplaceholder.typicode.com/photos",
{
params: {
albumId,
},
}
);
client.setEx("photos", DEFAULT_EXPIRATION, JSON.stringify(data.data));
res.json(data.data);
}
});
app.listen(3000, () => console.log("Listening on port 3000"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment