Skip to content

Sending API query

This tutorial is part of package functions documentation in Iconify Tools.

Function sendAPIQuery() is a wrapper for fetch with caching.

It is used by functions that retrieve text data from remote sources, such as importFromFigma() and downloadGitHubRepo().

To retrieve binary files, see downloadFile().

Usage

Function has the following parameters:

  • query, APIQueryParams. URI and parameters.
  • cache, APICacheOptions. Cache options.

Function returns:

  • Content as string on success.
  • Error as number on error.

Function is asynchronous. That means you need to handle it as Promise instance, usually by adding await before function call.

APIQueryParams

APIQueryParams object has the following properties:

  • uri, string. Base URI.
  • params, URLSearchParams. Optional parameters.
  • header, Record<string,string>. Optional headers.

Example:

jsconst params = {
   uri: 'https://api.whatever.com/some-file/',
   params: new URLSearchParams({
       version: '123',
   }),
   headers: {
       Accept: 'application/json',
   },
};

APICacheOptions

APICacheOptions object has the following properties:

  • dir, string. Directory where cache should be stored.
  • ttl, number. How long can data be cached, in seconds.

Cache management

If cache property is not set, data is not cached.

If cache property is set, function will generate unique hash for query, will check if file with that hash already exists, if it has not expired. On success it will return cached data instead of fetching new data.

You can purge cache at any time using clearAPICache() function:

tsimport { clearAPICache } from '@iconify/tools/lib/download/api/cache';

const cacheDir = 'cache';

// Asynchronous function, so wrapping it in anonymous async function.
// Not needed for Node 17+ that supports top level await.
(async () => {
   await clearAPICache(cacheDir);
})();

Example

example.ts
tsimport { sendAPIQuery } from '@iconify/tools';
import type { APICacheOptions } from '@iconify/tools/lib/download/api/types';

// 3 days cache
const ttl = 60 * 60 * 24 * 3;
const dir = 'cache/api';
const options: APICacheOptions = {
   dir,
   ttl,
};

(async () => {
   const data = await sendAPIQuery(
       {
           uri: 'https://api.iconify.design/collections',
       },
       options
   );
   console.log(typeof data === 'string' ? JSON.parse(data) : data);
})();

Released under the Apache 2.0 License.