@lidofinance/rpc
v0.64.0
Published
Fetch extension to use it with RPC endpoints
Readme
@lidofinance/rpc
Fetch extension to use it with RPC endpoints.
Installation
yarn add @lidofinance/rpc
Getting started
You can just use it as normal fetch, there are just a few types restrictions, and it will set right HTTP method for
you.
fetchRPC(url, { body: req.body })Examples
Caching
Here is an example how you can extend fetchRpc by adding caching
import { FetchRpc, fetchRpc } from '@lidofinance/rpc'
import { Cache } from 'memory-cache'
export type CachedFetchRPC = FetchRpc<{ cacheKey: string }>
// Just a sample how to use extend fetchRPC
export const cachedFetchRpcFactory = (timeout: number): CachedFetchRPC => {
const cache = new Cache<string, Response>()
return async (url, init, { cacheKey }) => {
const cachedValue = cache.get(cacheKey)
if (cachedValue != null) {
return cachedValue
}
const response = await fetchRpc(url, init)
cache.put(cacheKey, response, timeout)
return response
}
}iterateUrls fallback callback
iterateUrls(urls, callback, onError?) iterates provider URLs until one succeeds. The optional onError handler fires when an attempt fails — either the callback threw, or it returned a non-ok Response. The second argument carries context so you can log structured fallback transitions.
import { iterateUrls } from '@lidofinance/rpc'
await iterateUrls(
providers,
(url) => fetch(url),
(error, { failedUrl, nextUrl, attempt, response }) => {
if (nextUrl) {
logger.warn(`RPC ${failedUrl} failed (attempt ${attempt}), switching to ${nextUrl}`)
} else {
logger.error(`All RPC providers failed, last one was ${failedUrl}`)
}
},
)Handlers with a single-argument signature ((error) => ...) keep working — the extra context argument is simply ignored.
