Skip to content

Commit

Permalink
Add redis caching to make
Browse files Browse the repository at this point in the history
  • Loading branch information
ruchernchong committed Nov 22, 2024
1 parent 5131428 commit c7d5c0b
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/v1/routes/make.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Hono } from "hono";
import db from "../../config/db";
import type { Car } from "../../types";
import { deslugify } from "../../utils/slugify";
import redis from "../../config/redis";

const app = new Hono();

Expand All @@ -13,6 +14,13 @@ app.get("/:make", async (c) => {
const { make } = c.req.param();
const { month, fuelType, vehicleType } = c.req.query();

const cacheKey = `make:${make}`;

const cachedData = await redis.get(cacheKey);
if (cachedData) {
return c.json(cachedData);
}

const filter = {
...(make && {
make: new RegExp(`^${deslugify(make)}$`, "i"),
Expand All @@ -22,13 +30,15 @@ app.get("/:make", async (c) => {
...(vehicleType && { vehicle_type: new RegExp(vehicleType, "i") }),
};

return c.json(
await db
.collection<Car>("cars")
.find(filter)
.sort({ month: -1, fuel_type: 1, vehicle_type: 1 })
.toArray(),
);
const cars = await db
.collection<Car>("cars")
.find(filter)
.sort({ month: -1, fuel_type: 1, vehicle_type: 1 })
.toArray();

await redis.set(cacheKey, JSON.stringify(cars), { ex: 86400 });

return c.json(cars);
});

export default app;

0 comments on commit c7d5c0b

Please sign in to comment.