diff --git a/src/v1/routes/make.ts b/src/v1/routes/make.ts index bcb4cf8..e3283a5 100644 --- a/src/v1/routes/make.ts +++ b/src/v1/routes/make.ts @@ -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(); @@ -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"), @@ -22,13 +30,15 @@ app.get("/:make", async (c) => { ...(vehicleType && { vehicle_type: new RegExp(vehicleType, "i") }), }; - return c.json( - await db - .collection("cars") - .find(filter) - .sort({ month: -1, fuel_type: 1, vehicle_type: 1 }) - .toArray(), - ); + const cars = await db + .collection("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;