0.0.1 • Published 3 years ago

@breadman/async-cacher v0.0.1

Weekly downloads
-
License
-
Repository
github
Last release
3 years ago

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