Skip to content

Simple, zero-dependency utility for caching async functions.

Notifications You must be signed in to change notification settings

pBread/Async-Cacher

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Async Cacher

Simple, zero-dependency utility for caching async functions.

Contents

Features

  • Auto-cache async functions by arguments
  • Memory safe, weak-caching
  • Typescript support

Install

yarn add @breadman/async-cacher

Examples

import createAsyncCacher from "@breadman/async-cacher";
import fetch from "isomorphic-fetch";

interface Repo {
  id: number;
  name: string;
}

class GithubApi {
  cacher = createAsyncCacher(); // initialize new cache per instance

  async getRepos(user: string): Promise<Repo[]> {
    return fetch(`https://api.github.com/users/${user}/repos`).then((res) =>
      res.json()
    );
  }

  async getRepoCount(user: string): Promise<number> {
    const repos = await this.cacher<Repo[]>(this.getRepos, user);
    return repos.length;
  }

  async getRepoNames(user: string): Promise<string[]> {
    const repos = await this.cacher<Repo[]>(this.getRepos, user);
    return repos.map((repo) => repo.name);
  }
}

const api = new GithubApi();

await api.getRepoNames("pBread"); // fetches repos & returns array of names
await api.getRepoCount("pBread"); // retrieves repos from cache & returns count
await api.getRepoCount("markerikson"); // fetches repos

About

Simple, zero-dependency utility for caching async functions.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published