Skip to content

Commit

Permalink
feat: Add cache
Browse files Browse the repository at this point in the history
  • Loading branch information
ChefMomota committed Oct 24, 2024
1 parent b745d4b commit 74813ef
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/farms/src/fetchUniversalFarms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,25 @@ import { ERC20Token } from '@pancakeswap/sdk'
import { FARMS_API } from '../config/endpoint'
import { Protocol, UniversalFarmConfig } from './types'

const farmCache: Record<string, UniversalFarmConfig[]> = {}

export const fetchUniversalFarms = async (chainId: ChainId, protocol?: Protocol) => {
const cacheKey = `${chainId}-${protocol || 'all'}`

// Return cached data if it exists
if (farmCache[cacheKey]) {
return farmCache[cacheKey]
}

try {
const params = { chainId, ...(protocol && { protocol }) }
const queryString = Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&')

const response = await fetch(`${FARMS_API}?${queryString}`)
const response = await fetch(`${FARMS_API}?${queryString}`, {
signal: AbortSignal.timeout(3000),
})
const result = await response.json()
const newData: UniversalFarmConfig[] = result.map((p: any) => ({
...p,
Expand All @@ -32,6 +43,9 @@ export const fetchUniversalFarms = async (chainId: ChainId, protocol?: Protocol)
),
}))

// Cache the result before returning it
farmCache[cacheKey] = newData

return newData
} catch (error) {
return []
Expand Down

0 comments on commit 74813ef

Please sign in to comment.