Skip to content

Commit

Permalink
Debugging Upstash #11
Browse files Browse the repository at this point in the history
  • Loading branch information
david emioma committed Apr 3, 2024
1 parent f4f0d30 commit a330708
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 8 deletions.
2 changes: 1 addition & 1 deletion app/api/cart/[cartItemId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { z } from "zod";
import prismadb from "@/lib/prisma";
import { UserRole } from "@prisma/client";
import { NextResponse } from "next/server";
import { cacheCartData } from "@/data/redis-data";
import { currentRole, currentUser } from "@/lib/auth";
import { cacheCartData } from "@/data/redis-data";

export async function PATCH(
request: Request,
Expand Down
2 changes: 1 addition & 1 deletion app/api/cart/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { UserRole } from "@prisma/client";
import { NextResponse } from "next/server";
import { currentRole, currentUser } from "@/lib/auth";
import { CartItemSchema } from "@/lib/validators/cart-item";
import { getCachedCartData, cacheCartData } from "@/data/redis-data";
import { cacheCartData, getCachedCartData } from "@/data/redis-data";

export async function POST(request: Request) {
try {
Expand Down
6 changes: 2 additions & 4 deletions data/redis-data.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
"use server";

import prismadb from "@/lib/prisma";
import { redis } from "@/lib/redis";

export const getCachedCartData = async (userId: string) => {
export const getCachedCartData = async (userId?: string) => {
if (!userId) return null;

const cachedCart = await redis.get(`${userId}-cart`);

return cachedCart;
};

export const cacheCartData = async (userId: string) => {
export const cacheCartData = async (userId?: string) => {
if (!userId) return;

const cart = await prismadb.cart.findUnique({
Expand Down
14 changes: 12 additions & 2 deletions lib/redis.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import { Redis } from "@upstash/redis";
import { Ratelimit } from "@upstash/ratelimit";

const url = process.env.NEXT_PUBLIC_UPSTASH_REDIS_REST_URL;

const token = process.env.NEXT_PUBLIC_UPSTASH_REDIS_REST_TOKEN;

if (!url || !token) {
throw new Error(
"Redis URL or Token is not defined in environment variables."
);
}

export const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL as string,
token: process.env.UPSTASH_REDIS_REST_TOKEN as string,
url,
token,
});

export const apiRatelimit = new Ratelimit({
Expand Down

0 comments on commit a330708

Please sign in to comment.