From 602cebae27d373eb684702727844c315ee57a25e Mon Sep 17 00:00:00 2001 From: bensigo Date: Wed, 4 Oct 2023 16:53:17 +0400 Subject: [PATCH] feat: adding cache to activities api --- src/server/api/routers/activities.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/server/api/routers/activities.ts b/src/server/api/routers/activities.ts index 7dc0019..1b575c5 100644 --- a/src/server/api/routers/activities.ts +++ b/src/server/api/routers/activities.ts @@ -4,6 +4,7 @@ import { queryOpenAi } from "@/utils/openai"; import { DailyQuestActivity, Level } from "@prisma/client"; import { getLevel } from "../utils"; import { createChat } from "./chat"; +import { kv } from "@vercel/kv"; interface Activity { title: string; @@ -27,6 +28,17 @@ export const activityRouter = createTRPCRouter({ try { const prisma = ctx.prisma; + // check for cache + const cacheKey = `${ctx.session.user.id}_affirmation` + const cacheData = await kv.get(cacheKey); + + console.log({ cacheData }) // log for texting + + if(cacheData) { + const data = (JSON.parse(cacheData) )as Activity[]; + return data + } + // const quest = await ctx.prisma.quest.findUnique({ where: { id: input.questId }, include: { goal: true }}) const quest = await prisma.quest.findFirst({ where: { id : input.questId }, @@ -56,6 +68,12 @@ export const activityRouter = createTRPCRouter({ } const activities = parseActivities(rawActivitiyResponse); console.log({ activities }) + + // set cache data + const currentCache = JSON.stringify(activities) + await kv.set(cacheKey, currentCache, { + ex: 86400 + }) return activities; } @@ -245,6 +263,8 @@ export const activityRouter = createTRPCRouter({ type: z.enum(dailyActivityEnum) })).query(async ({ ctx, input }) => { + + const activity = ctx.prisma.dailyActivity.findFirst({ where: { type: input.type as DailyQuestActivity,