npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@darkair/api-cache

v1.3.1

Published

This is a small lib on TypeScript to give you an easy way to cache API requests. Instead of caching every API request and solving concurrent event issues, you can write clean, readable code.

Downloads

10

Readme

API Cache

This is a small lib on TypeScript to give you an easy way to cache API requests. Instead of caching every API request and solving concurrent event issues, you can write clean, readable code.

Installation

npm i @darkair/api-cache

Usage

At first, you need to extend the interface ICache to declare your own properties for caching. Also you have to create ApiCache extends from the class AbstractApiCache:

import {ICache, AbstractApiCache, CacheValue, CacheArrayValue, makeCacheValue, makeCacheArray} from '@darkair/api-cache';

interface Cache extends ICache {
    prop1: CacheValue<User[]>,        // Caching single value
    prop2: CacheArrayValue<User>,     // Caching array of specified values by unique keys
}

class ApiCache extends AbstractApiCache<Cache> {
    protected cache: Record<keyof Cache, any> = {
        prop1: makeCacheValue<User[]>([]),
        prop2: makeCacheArray<User>(null),
    };
}

const apiCache: ApiCache = new ApiCache();
export default apiCache;

Next, you can use your apiCache in your code. For example:

/**
 * Get a single value
 * Returns User[] or empty array (default value, specified in cache class)
 */
fetchUsers(): Promise<User[]> {
    return apiCache.getValue('prop1', async (): Promise<User[]> => {
        return fetch('/getUsers')
            .then(data => data.json());
    });
}

/**
 * Get an value of type User from cached array by UNIQ_KEY
 * Returns User or null (default value, specified in cache class)
 */
getUser(id: number): Promise<User> {
    return apiCache.getArrayValue('prop2', id, async (): Promise<User> => {
        return fetch('/getUser', {method: 'post', body: `{"id":${id}}`})
            .then(data => data.json());
    });
}

Now you can call the methods above when and where you want in your asynchronous code without any unneeded conditions. You will have a guarantee that all of your requests will get the correct data.

// You are guaranteed to have an array with data or empty array
const users: User[] = await fetchUsers();
users.forEach((user: User) => {...});


// Code below send only 5 request (not 5000)
for (let j = 1; j < 1000; j++) {
    for (let i = 1; i < 5; i++) {
        const user: User = getUser(i);
        
        // Here 'user' will be eather only User or null
    }
}

Documentation

Type of single cached value.
interface CacheValue<T>
Type of array with the cached values.
interface CacheArrayValue<T>
Helper function to create the structure for single cached value.
function makeCacheValue<T>(defValue: T): CacheValue<T>
Helper function to create the structure for array with the cached values.
function makeCacheArray<T>(defValue: T): CacheArrayValue<T>
Cache structure interface
interface ICache {
    // Your data
}
IApiCache interface
interface IApiCache<TCache extends ICache> {
    /**
     * Get the value by the key of Cache interface
     */
    getValue<T>(name: keyof TCache, func: () => Promise<T>): Promise<T>;

    /**
     * Get the value of array by the key of Cache interface and uniqKey
     */ 
    getArrayValue<T>(name: keyof TCache, key: string, func: () => Promise<T>): Promise<T>;

    /**
     * Invalidate the value addressed by the key of Cache interface
     */
    invalidate(name: keyof TCache): void;

    /**
     * Invalidate whole cache
     */
    invalidateAll(): void;

    /**
     * Subscribe to cache invalidation
     */
    subscribe(name: keyof TCache, callback: () => void): () => void;
}
Abstract class to extends with your own cache
abstract class AbstractApiCache<TCache extends ICache> implements IApiCache<TCache> {
    protected cache: Record<keyof Cache, any> = {
        // Your data
    }
}