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

cajache

v2.0.2

Published

Simple javascript cache

Downloads

165

Readme

cajache package size cajache package size minzipped cajache dependency count

cajache is a minimalistic javascript caching library.

  • ⚡ Optimizes your projects reducing the number of HTTP request or heavy actions performed.
  • 🚀 Lightweight.
  • ⚪️ Zero dependencies.

Table of contents

Import

const cajache = require("cajache");

Quick start

Permanent cache

const myFetchFnc = axios.get("https://your.api/resource");

const response = await cajache.use(
    "cache_id_01",
    myFetchFnc
);
// The first time it will execute myFetchFnc.

const cachedResponse = await cajache.use(
    "cache_id_01",
    myFetchFnc
);
// The second time it will return cached value instead re-executing myFetchFnc.

Temporal cache

const myFetchFnc = axios.get("https://your.api/resource");

const response = await cajache.use(
    "cache_id_01",
    myFetchFnc,
    {
        ttl: 1000, // 1 second
    }
);
// The first time it will execute myFetchFnc.

// Sleep 3
await new Promise(res => setTimeout(res, 3000));

const nonCachedResponse = await cajache.use(
    "cache_id_01",
    myFetchFnc,
    {
        ttl: 1000, // 1 second
    }
);
// The second time it will NOT return cached value because it's expired.

Creating a new instance

const cajache = require("cajache");
const myInstance = cajache.new();

Instance options

const cajache = cajache(options);

| Instance option | Type | Description | :-----------: |:-------------: | :----- | ttl | number | Default 0. Default TTL in miliseconds for all cached values. 0 = permanent | checkInterval | function | Default 1000 * 60 (1 min). Interval in miliseconds to check if cached values with ttl are expired. | path | string | Dot path to the property that will be cached. Example: "axiosResponse.data". | condition | function | On cache miss, this function will receive as argument the response of fnc. If it returns true the response will be cached, if it returns false it won't be cached.

Use cases

Cache HTTP requests


// fetch 1: 248.659ms
// fetch 2 (cached): 0.015ms
// fetch 3 (cached): 0.008ms


console.time("fetch 1");

let characters = await cajache.use(
    "characters",
    () => axios.get("https://rickandmortyapi.com/api/character/14"),
);

console.timeEnd("fetch 1");
console.time("fetch 2 (cached)");

characters = await cajache.use(
    "characters",
    () => axios.get("https://rickandmortyapi.com/api/character/14"),
);

console.timeEnd("fetch 2 (cached)");



console.time("fetch 3 (cached)");
await cajache.use(
    "characters",
    () => axios.get("https://rickandmortyapi.com/api/character/14"),
);
console.timeEnd("fetch 3 (cached)");

Cache paginated HTTP requests


// fetch page 1: 284.629ms
// fetch page 2: 208.210ms
// fetch page 1 (cached): 0.018ms
// fetch page 2 (cached): 0.008ms


console.time("fetch page 1");

let characters_page1 = await cajache.use(
    ["characters", "page_1"],
    () => axios.get("https://rickandmortyapi.com/api/character/?page=1"),
);

console.timeEnd("fetch page 1");
console.time("fetch page 2");

let characters_page2 = await cajache.use(
    ["characters", "page_2"],
    () => axios.get("https://rickandmortyapi.com/api/character/?page=2"),
);

console.timeEnd("fetch page 2");



console.time("fetch page 1 (cached)");

characters_page1 = await cajache.use(
    ["characters", "page_1"],
    () => axios.get("https://rickandmortyapi.com/api/character/?page=1"),
);

console.timeEnd("fetch page 1 (cached)");
console.time("fetch page 2 (cached)");

characters_page2 = await cajache.use(
    ["characters", "page_2"],
    () => axios.get("https://rickandmortyapi.com/api/character/?page=2"),
);

console.timeEnd("fetch page 2 (cached)");

API

.use

Syntax:

const cachedResponse: Promise = cajache.use(
    id: "myId",
    fetchFnc: () => stuff,
    options: {},
);

| Parameter | Type | Description | | :-----------: |:-------------: | :----- | | id | string | Array<string> | Unique identifier of the cache entry. If you pass an array like ["parent", "child"] it will be treated as deep nested id. If parent is deleted all children will be deleted too. | fnc | function | Your function that will be cached. Can be async. | options | object | Same as instance options (without checkInterval). If set, it will override instance options, otherwise it will use them.

Example:

// Simple id
const response = await cajache.use(
    "characters",
    () => axios.get("https://you.api.com/characters"),
);
// Nested id
const response = await cajache.use(
    ["location_2",  "characters", "page_3"],
    () => axios.get("https://you.api.com/location2/characters?page=3"),
);

Example with expire:

const response = await cajache.use(
    ["location_2", "characters", "page_3"],
    () => axios.get("https://you.api.com/location2/characters?page=3"),
    {
        expire: 1000 * 30, // 30 seconds
    }
);

Example with path:

const response = await cajache.use(
    ["location_2", "characters", "page_3"],
    () => axios.get("https://you.api.com/location2/characters?page=3"),
    {
        path: "character.name",
    }
);

Example with condition:

const response = await cajache.use(
    ["location_2", "characters", "page_3"],
    () => axios.get("https://you.api.com/location2/characters?page=3"),
    {
        condition: apiRes => apiRes.isError === false,
    }
);

.get

Syntax:

cajache.get(id);

| Parameter | Type | Description | | :-----------: |:-------------: | :----- | | id | string | Array<string> | Unique identifier of the cache entry

Or...

const location2_characters_page3 = cajache.get(["location_2", "characters", "page_3"]);

.set

Syntax:

cajache.set(id, value );

| Parameter | Type | Description | | :-----------: |:-------------: | :----- | | id | string | Array<string> | Unique identifier of the cache entry | value | any | Value you want to set

Examples:

cajache.set("characters", {...} );

Or...

cajache.set(["location_2", "characters", "page_3"], {...} );

.delete

Syntax;

cajache.delete(id);

| Parameter | Type | Description | | :-----------: |:-------------: | :----- | | id | string | Array<string> | Unique identifier of the cache entry you want to delete.

Delete location_2 cache entry (and his childrens):

cajache.delete("location_2");

Delete location_2.characters.page_3 cache entry (and his childrens):

.deleteAll

Deletes all cache entries of the instance.

cajache.deleteAll();

.setConfig

Sets the instance config.

cajache.setConfig(key, value);

Keys and values are the same as instance options.

Example:

cajache.setConfig("checkInterval", 1000 * 60 * 5); // 5 minutes

TTL watcher

  • It starts automatically when you create any instance.
  • It will only iterate over all cache entries with TTL.
  • It will delete all expired cache entries every config.checkInterval milliseconds.
  • It will check the instance config (config?.checkInterval) after each iteration to stop or continue the loop.
  • If the checkInterval is changed it will not not be effective until the next iteration.

Go to top