fix: add args as keyParts for unstable_cache

This commit is contained in:
Christel Westerberg
2024-10-09 11:27:16 +02:00
committed by Pontus Dreij
parent ea8fdc940d
commit ed3acce57c
7 changed files with 204 additions and 186 deletions
+18 -19
View File
@@ -5,24 +5,22 @@ import { env } from "@/env/server"
import { generateServiceTokenTag } from "@/utils/generateTag"
import { ServiceTokenScopeEnum } from "@/types/enums/serviceToken"
import { ServiceTokenResponse } from "@/types/tokens"
// OpenTelemetry metrics: Service token
const meter = metrics.getMeter("trpc.context.serviceToken")
const getServiceTokenCounter = meter.createCounter(
"trpc.context.serviceToken.get-new-token"
const fetchServiceTokenCounter = meter.createCounter(
"trpc.context.serviceToken.fetch-new-token"
)
const getTempServiceTokenCounter = meter.createCounter(
"trpc.context.serviceToken.get-temporary"
const fetchTempServiceTokenCounter = meter.createCounter(
"trpc.context.serviceToken.fetch-temporary"
)
const getServiceTokenFailCounter = meter.createCounter(
"trpc.context.serviceToken.get-fail"
const fetchServiceTokenFailCounter = meter.createCounter(
"trpc.context.serviceToken.fetch-fail"
)
async function getServiceToken() {
getServiceTokenCounter.add(1)
const scopes = Object.keys(ServiceTokenScopeEnum)
async function fetchServiceToken(scopes: string[]) {
fetchServiceTokenCounter.add(1)
const response = await fetch(`${env.CURITY_ISSUER_USER}/oauth/v2/token`, {
method: "POST",
headers: {
@@ -38,7 +36,7 @@ async function getServiceToken() {
})
if (!response.ok) {
getServiceTokenFailCounter.add(1, {
fetchServiceTokenFailCounter.add(1, {
error_type: "http_error",
error: JSON.stringify({
status: response.status,
@@ -51,21 +49,22 @@ async function getServiceToken() {
return response.json()
}
export async function fetchServiceToken(): Promise<ServiceTokenResponse> {
export async function getServiceToken(): Promise<ServiceTokenResponse> {
try {
const tag = generateServiceTokenTag()
const scopes = ["profile", "hotel", "booking"]
const tag = generateServiceTokenTag(scopes)
const getCachedJwt = unstable_cache(
async () => {
const jwt = await getServiceToken()
async (scopes) => {
const jwt = await fetchServiceToken(scopes)
const expiresAt = Date.now() + jwt.expires_in * 1000
return { expiresAt, jwt }
},
[],
[tag],
{ tags: [tag] }
)
const cachedJwt = await getCachedJwt()
const cachedJwt = await getCachedJwt(scopes)
if (cachedJwt.expiresAt < Date.now()) {
console.log(
"trpc.context.serviceToken: Service token expired, revalidating tag"
@@ -75,8 +74,8 @@ export async function fetchServiceToken(): Promise<ServiceTokenResponse> {
console.log(
"trpc.context.serviceToken: Fetching new temporary service token."
)
getTempServiceTokenCounter.add(1)
const newToken = await getServiceToken()
fetchTempServiceTokenCounter.add(1)
const newToken = await fetchServiceToken(scopes)
return newToken
}