Caching Data

This guide will help you get started with caching data from the API.

When you start fetching data from the API, we ask that you cache the data to prevent unnecessary requests to the API. If you need to update the data, you can do so by setting up a cron job to fetch the data at a specific interval.

Caching Data

To cache data from the API, you can use the following code snippet:

cache.ts
import { Cache } from 'vtubers';

const cache = new Cache();

// Set a key-value pair with an expiration time of 
// 1 hour 30 minutes and 15 seconds
cache.set('myKey', 'myValue', '1h,30m,15s');

// Get the value of the key
const value = cache.get('myKey');

console.log(value); // > myValue

// Delete the key
cache.delete('myKey');

// Clear the cache
cache.clear();

// Check if the cache has a key
const hasKey = cache.has('myKey');

console.log(hasKey); // > false

// Get the size of the cache
const size = cache.size;

console.log(size); // > 0

// Get all the keys in the cache
const keys = cache.keys();

console.log(keys); // > []

Using the Cache with Fetch

To use the cache with the fetch() function, you can use the following code snippet:

fetch_with_cache.ts
import { fetch, Cache } from 'vtubers';

const cache = new Cache();

const dataFromRequest = await fetch('users/someUsername', {
    method: 'GET',
    query: {
        someKey: 'someValue',
    },
    headers: {
        'X-My-Header': 'someValue',
    },
    body: {
        someKey: 'someValue',
    },
});

// Cache the data with a key of 'someUsername'
cache.set('someUsername', dataFromRequest, '1h');

console.log(data);

Automatic Cache Cleanup

You can set up automatic cache cleanup based on the size of the cache. To do this, you can use the following code snippet:

cache_cleanup.ts
import { Cache } from 'vtubers';

const cache = new Cache({
  cleanupOnSize: 10,
});

In this example, the cache will automatically clean up when the size of the cache reaches 10 items. You can set the cleanupOnSize option to any number you want however you can't go above 1.7976931348623157e+308 which is the Number.MAX_VALUE value.