I am trying to add in the KV Storage into the server side API code to help performance. I found that I am successful at setting the value in the KV store but retrieving it always returns a null value.
Import Line
import { kv } from '@vercel/kv';Function
// Get sport_id by sport keyexport async function getSportID(sport_key: string): Promise<number> { try { const startTime = Date.now(); const cacheKey = `sport_${sport_key}`; console.log("cacheKey", cacheKey); if (await kv.exists(cacheKey)) { const cachedSport = await kv.get(cacheKey); console.log("cachedSport", cachedSport); if (cachedSport) { console.log("Returned from cache"); return cachedSport as unknown as number; } } console.log("Returned from db"); const pool = await initializePool(); const sport = await pool.any( sql.unsafe` SELECT sport_id FROM sport WHERE key = ${sport_key} ` ); const sport_id = sport?.[0]?.sport_id; console.log("sport_id", sport_id); const setSportResult = await kv.set(cacheKey,sport_id); console.log("setSportResult", setSportResult); const endTime = Date.now(); console.log("Time taken to get sport_id", endTime - startTime); return sport_id; } catch (error) { console.error('Failed to fetch sport:', error); throw new Error('Unable to retrieve sport'); }}Console output when I run it.
cacheKey sport_basketball_wnbacachedSport nullReturned from dbsport_id 15setSportResult OKTime taken to get sport_id 1243When I run the CLI in the browser it also works
GET sport_basketball_wnba15