fix: wrap tier rewards endpoint in unstable_cache

This commit is contained in:
Christel Westerberg
2024-10-09 15:20:00 +02:00
committed by Pontus Dreij
parent ed3acce57c
commit 2886f537ee

View File

@@ -1,10 +1,10 @@
import { metrics } from "@opentelemetry/api"
import { unstable_cache } from "next/cache"
import { Lang } from "@/constants/languages"
import * as api from "@/lib/api"
import { GetRewards } from "@/lib/graphql/Query/Rewards.graphql"
import { request } from "@/lib/graphql/request"
import { Context } from "@/server/context"
import { notFound } from "@/server/errors/trpc"
import {
contentStackBaseWithProtectedProcedure,
@@ -62,19 +62,19 @@ const getAllRewardFailCounter = meter.createCounter(
"trpc.contentstack.reward.all-fail"
)
const ONE_HOUR = 60 * 60
function getUniqueRewardIds(rewardIds: string[]) {
const uniqueRewardIds = new Set(rewardIds)
return Array.from(uniqueRewardIds)
}
async function getAllApiRewards(ctx: Context & { serviceToken: string }) {
const getAllCachedApiRewards = unstable_cache(
async function (token) {
const apiResponse = await api.get(api.endpoints.v1.tierRewards, {
cache: undefined, // override defaultOptions
headers: {
Authorization: `Bearer ${ctx.serviceToken}`,
Authorization: `Bearer ${token}`,
},
// One hour. Since the service token is refreshed every hour, this is the longest cache we can have.
next: { revalidate: 60 * 60 },
})
if (!apiResponse.ok) {
@@ -118,13 +118,15 @@ async function getAllApiRewards(ctx: Context & { serviceToken: string }) {
}
return validatedApiTierRewards.data
}
},
["getAllApiRewards"],
{ revalidate: ONE_HOUR }
)
async function getCmsRewards(locale: Lang, rewardIds: string[]) {
const tags = rewardIds.map((id) =>
generateLoyaltyConfigTag(locale, "reward", id)
)
const cmsRewardsResponse = await request<CmsRewardsResponse>(
GetRewards,
{
@@ -266,7 +268,9 @@ export const rewardQueryRouter = router({
getByLevelRewardCounter.add(1)
const { level_id } = input
const allUpcomingApiRewards = await getAllApiRewards(ctx)
const allUpcomingApiRewards = await getAllCachedApiRewards(
ctx.serviceToken
)
if (!allUpcomingApiRewards || !allUpcomingApiRewards[level_id]) {
getByLevelRewardFailCounter.add(1)
@@ -314,7 +318,7 @@ export const rewardQueryRouter = router({
.input(rewardsAllInput)
.query(async function ({ input, ctx }) {
getAllRewardCounter.add(1)
const allApiRewards = await getAllApiRewards(ctx)
const allApiRewards = await getAllCachedApiRewards(ctx.serviceToken)
if (!allApiRewards) {
return []