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

dyna-cache

v3.0.3

Published

Cache with controlled memory consumption

Downloads

14

Readme

DynaCache v3

Caches something and provides it immediately.

Preload, refresh features out of the box.

createDynaCache

This factory function creates another function that uses the cache behind this.

Example

Suppose we have this interface of articles

interface ITestArticle {
  title: string;
  body: string;
}

And this api method that loads the articles from the backend

const apiLoadArticles = async (args: {lang: string, group: string}): Promise<ITestArticle[]> => [];

Let's make api method cacheable version of it

const apiLoadArticlesCacheEngine = createDynaCache({
  load: apiLoadArticles,
  expireAfterMinutes: 10,
});

The apiLoadArticlesCacheEngine is na object, with the load(args: TArgs) method that returns data.

Thanks to typescript, the function has all types obtained from the load method, for the args and for the output. So we don't have to define anything to the generics of the createDynaCache.

Let's use it


apiLoadArticlesCacheEngine.load({lang: 'en', group: 'fashion'})     // We pass the object as we do with the apiLoadArticles
  .then(articles => {
    // We have types articles here
    articles.forEach(article => {
      console.log('Title', article.title);
    });
  });

Configuration object of the createDynaCache

interface ICreateDynaCacheConfig<TArgs, TData, > {
  load: (args: TArgs) => Promise<TData>; // The load operation
  expireAfterMinutes?: number;            // When the cache expires, undefined for none
  preload?: boolean;                      // Preload the data on start
  refreshEveryMinutes?: number;           // Refresh the data silently on background
}

Invalidate the cache

To invalidate the cache (to clear the content of the cache) call the invalidate()

apiLoadArticlesCacheEngine.invalidate();

Don't forget to free() it!

Cache keeps resources for refreshing, etc.

If you are going to free the owner of it, your have to call the .free() also!

Just apiLoadArticlesCacheEngine.free().

How does it works internally?

The apiLoadArticlesCacheEngine creates internally small caches for each different args.

If you ask the same args, then the cached version will be served.

DynaCache

This is how to create a DynaCache class.

Config

 interface IDynaCacheConfig<TData> {
  load: () => Promise<TData>;       // The load operation

  expireAfterMinutes?: number;      // When the cache expires, undefined for none
  preload?: boolean;                // Preload the data on start
  refreshEveryMinutes?: number;     // Refresh the data silently on background
  onLoad?: (data: TData) => void;   // Called when the data are loaded for any reason
}

Methods

  • load(): Promise<TData> load from cache or from source if it is not yet cached
  • loadFresh(): Promise<TData> load fresh data (not from cache)
  • invalidate(): void clear the cache, all further loads will be new
  • free(): void destroy the cache (cleans up auto refresh cache)

Properties

  • get size(): number returns the size of the cache in bytes
  • get loadedAt(): number timestamp when the last load took place
  • get lastUsedAt(): number timestamp when the cache read last time
  • get loadCount(): number how many the cache was updated
  • get lastError(): any last load error

Example

// Factory function that create a DynaCache with specific args and api method
// This function just connects that arguments with the api method
const createLoadArticlesCache = (lang: string, group: string) =>
  new DynaCache({
    expireAfterMinutes: 10,
    load: () => apiLoadArticles(lang, group),
  });

// Lets create a cache for the epi
const loadArticlesCache = createLoadArticlesCache('en', 'fashion');

// Lets use it
loadArticlesCache.load(); // The return is always up to date and fast

// Don't forget to free() it to avoid memory leaks!
// This is needed when `expireAfterMinutes` or `refreshEveryMinutes`
loadArticlesCache.free();
// Note, now you cannot use it anymore

Change log

v3

V3 is totally different approach than V2.

V3 offers plus

  • preload
  • refresh
  • cache factory (cache key by args object)
  • simpler code (1/4 of the previous one)

v2

For v2 open this page.