Skip to content

Commit

Permalink
adding redis to the fetch requests
Browse files Browse the repository at this point in the history
  • Loading branch information
abhinav700 committed Dec 2, 2024
1 parent 53124be commit af9538f
Show file tree
Hide file tree
Showing 12 changed files with 317 additions and 92 deletions.
9 changes: 7 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
DATABASE_URL=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
NEXT_PUBIC_BASE_URL=
SECRET=
SECRET=
POSTGRES_USER="postgres"
POSTGRES_PASSWORD="postgres"
POSTGRES_DB="testimonial_space"
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}
REDIS_HOST="localhost"
REDIS_PORT=6379
28 changes: 28 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
version: '3.8'

services:
redis:
image: redis:latest
container_name: redis
ports:
- "6379:6379"
volumes:
- redis_data:/data

postgres:
image: postgres:latest
container_name: postgres
ports:
- "5432:5432"
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
volumes:
- postgres_data:/var/lib/postgresql/data

volumes:
redis_data:
postgres_data:


98 changes: 92 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"dependencies": {
"@prisma/client": "^5.20.0",
"axios": "^1.7.7",
"ioredis": "^5.4.1",
"lucide-react": "^0.453.0",
"next": "14.2.13",
"next-auth": "^4.24.8",
Expand All @@ -19,7 +20,7 @@
"zod": "^3.23.8"
},
"devDependencies": {
"@types/node": "^20",
"@types/node": "^20.17.9",
"@types/react": "^18",
"@types/react-dom": "^18",
"commitizen": "^4.3.1",
Expand Down
14 changes: 14 additions & 0 deletions redis/redis.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Redis } from "ioredis";

export class RedisManager {
static instance: Redis;

getInstance: () => Redis = () => {
if (!RedisManager.instance) RedisManager.instance = new Redis();
return RedisManager.instance;
};
}

export const redisManager = new RedisManager();

export const redisClient = redisManager.getInstance();
4 changes: 4 additions & 0 deletions src/app/(user)/page.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
/**
* Styles don't load properly if we don't use it as a client component
*/
"use client"
import LandingPage from "@/components/LandingPage/LandingPage";

export default function Home() {
Expand Down
39 changes: 26 additions & 13 deletions src/app/api/space/fetchAll/route.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,39 @@
import { prisma } from "@/prisma/client";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { redisClient } from "@redis/redis";

export const emailSchema = z.string().email("invalid email")
export const emailSchema = z.string().email("invalid email");

export async function GET(req: NextRequest){
export async function GET(req: NextRequest) {
try {
// To do : Replace with user id
const email = emailSchema.parse(req.nextUrl.searchParams.get("email"));

const spaces = await prisma.space.findMany({
where:{
ownerEmail: email
},
include: {
testimonials: true,
}
});

return NextResponse.json({spaces, status : 200});
/**
* caching spaces of a email
*/
const redisKey = `spaces[email]:${email}`;
const cachedData = await redisClient.get(redisKey);
let spaces;

if (cachedData != null) {
spaces = await JSON.parse(cachedData);
} else {
spaces = await prisma.space.findMany({
where: {
ownerEmail: email,
},
include: {
testimonials: true,
},
});
await redisClient.setex(redisKey, 2 * 3600, JSON.stringify(spaces));
}

return NextResponse.json({ spaces, status: 200 });
} catch (error) {
console.log(error);
return NextResponse.json({ error: "An error occurred" }, { status: 500 });
}
}
}
47 changes: 31 additions & 16 deletions src/app/api/space/fetchByName/route.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,38 @@
import { prisma } from "@/prisma/client";
import { redisClient } from "@redis/redis";
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest){
export async function GET(req: NextRequest) {
try {
const spaceName:string = req.nextUrl.searchParams.get("spaceName")!;
const space = await prisma.space.findFirst({
where:{
spaceName
},
include:{
testimonials: true
}
});
if(!space)
return NextResponse.json({msg:"Space does not exist", status:401});

return NextResponse.json({status: 200, msg: "success", space});
const spaceName: string = req.nextUrl.searchParams.get("spaceName")!;

/**
* storing the data related to a space
*/
const redisKey: string = `space[name]:${spaceName}`;
const cachedData = await redisClient.get(redisKey);

let space;

if (cachedData != null) {
space = await JSON.parse(cachedData);
} else {
space = await prisma.space.findFirst({
where: {
spaceName,
},
include: {
testimonials: true,
},
});
await redisClient.setex(redisKey, 2 * 3600, JSON.stringify(space));
}
if (!space)
return NextResponse.json({ msg: "Space does not exist", status: 401 });

return NextResponse.json({ status: 200, msg: "success", space });
} catch (error) {
console.log(error);
return NextResponse.json({status:401, msg: "Internal server error"});
return NextResponse.json({ status: 401, msg: "Internal server error" });
}
}
}
Loading

0 comments on commit af9538f

Please sign in to comment.