Free API Services only Allow X Calls Per Month – node-fetch-cache to the Rescue

Written by James McDonald

August 24, 2021

Just been trying to create a Node App that will query the Binance Dex web page for my wallets address and then take the estimated USD value and convert it to AUD

So you need an API to get a conversion factor

https://openexchangerates.org/

I am using the above

But when you only have a limited number requests a month, on the free plan, and you only care about the quoted exchange rate being close to within a day you can use https://www.npmjs.com/package/node-fetch-cache which will allow you to set an in memory cache of the request and then serve it from cache or when it expires or the request parameters change

import { fetchBuilder, MemoryCache } from 'node-fetch-cache';
const options { 
    ttl: 1000 * 60 * 60 * 24 // 24 hours in milliseconds
};
const fetch = fetchBuilder.withCache(new MemoryCache(options));

fetch('https://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID_HERE&symbols=AUD')
  .then(async response => {
    if (!response.ok) {
      await response.ejectFromCache();
      throw new Error('Non-okay response from google.com');
    } else {
      return response.json();
    }
  }).then(json => console.log(json));

The above refreshes the USD to AUD exchange rate once a day, when the request parameters change, the cached value times out, or whenever the node process restarts.

Why? This will stop you hitting your free API request limit and then it stopping working.

node-fetch-cache didn’t seem to have a Typescript types library so I created a “decs.d.ts” file with the following content to stop VS Code complaining about the missing types. I put it in my rootDir which is specified in tsconfig.json as ./src

// src/decs.d.ts
// put this file where the typescript compiler (tsc) can find it
// you can also add the path to this to the include param in tsconfig.json
declare module "node-fetch-cache"

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…