Skip to content

Commit

Permalink
feat: add cache layer for daily affirmations
Browse files Browse the repository at this point in the history
  • Loading branch information
Bensigo committed Oct 4, 2023
1 parent b2a7f9a commit e9c30bc
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/server/api/routers/affirmation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { extractArrayFromString, queryOpenAi } from "@/utils/openai";
import { createTRPCRouter, protectedProcedure } from "../trpc";
import { kv } from "@vercel/kv";

const aiPromptForAffirmations = `I want you to generate 8 affirmation, to brighting my day. return answer in an array format, without indexing`

Expand All @@ -26,6 +27,15 @@ export const affirmationRoutes = createTRPCRouter({
getDailyAffirmations: protectedProcedure.query(async ({ ctx }) => {
const prisma = ctx.prisma;
const user = ctx.session.user;


const cacheKey = `${user.id}_daily_affirmations`;
const cacheAffirmations = await kv.get<string[]>(cacheKey);

if (cacheAffirmations && cacheAffirmations.length){
return cacheAffirmations;
}

const prompt = aiPromptForAffirmations;
const quest = await prisma.quest.findFirst({
where: {
Expand Down Expand Up @@ -54,6 +64,13 @@ export const affirmationRoutes = createTRPCRouter({
throw new Error('Opps something went wrong try again')
}
const affirmations = extractArrayFromString(rawResp);


// cache affirmations
await kv.set(cacheKey, affirmations, {
ex: 86400
})

return affirmations


Expand All @@ -62,6 +79,15 @@ export const affirmationRoutes = createTRPCRouter({
const prisma = ctx.prisma;
const user = ctx.session.user;


const cacheKey = `${user.id}_affirmations`;
const cacheAffirmations = await kv.get<string[]>(cacheKey);

if (cacheAffirmations && cacheAffirmations.length){
return cacheAffirmations;
}


const quest = await prisma.quest.findFirst({
where: {
userId: user.id,
Expand All @@ -78,6 +104,11 @@ export const affirmationRoutes = createTRPCRouter({
const rawResp = (await queryOpenAi(prompt)) as string

const affirmations = extractArrayFromString(rawResp);

// cache affirmations
await kv.set(cacheKey, affirmations, {
ex: 86400
})


return affirmations;
Expand Down

0 comments on commit e9c30bc

Please sign in to comment.