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

api-response-cache

v1.0.3

Published

A lightweight library for caching API responses

Readme

API Response Cache

A lightweight library for caching API responses in JavaScript and TypeScript applications. This helps reduce redundant API calls and improves performance by storing responses for a specified duration.


Features

  • Simple and easy-to-use API.
  • Supports both JavaScript and TypeScript.
  • Configurable cache duration for each entry.
  • In-memory caching mechanism for quick access.
  • Automatic cache invalidation after expiration.

Installation

Install the package via NPM:

npm install api-response-cache

Usage

TypeScript Example

import ApiResponseCache from 'api-response-cache';

const cache = new ApiResponseCache();

// Add data to the cache with a 5-minute expiration
cache.set('user-data', { name: 'John', age: 30 }, 300000);

// Retrieve cached data
const data = cache.get<{ name: string; age: number }>('user-data');
console.log(data); // { name: 'John', age: 30 }

// Clear all cache entries
cache.clear();

JavaScript Example

const ApiResponseCache = require('api-response-cache');

const cache = new ApiResponseCache();

// Add data to the cache with a 5-minute expiration
cache.set('user-data', { name: 'John', age: 30 }, 300000);

// Retrieve cached data
const data = cache.get('user-data');
console.log(data); // { name: 'John', age: 30 }

// Clear all cache entries
cache.clear();

API Reference

ApiResponseCache

Constructor

Creates an instance of the cache.

const cache = new ApiResponseCache();

Methods

  1. set(key: string, value: any, duration?: number): void

    • Description: Adds a value to the cache with an optional expiration time.
    • Parameters:
      • key (string): The unique identifier for the cache entry.
      • value (any): The data to store in the cache.
      • duration (number, optional): Time in milliseconds for which the data should remain in the cache. Defaults to 300,000 ms (5 minutes).
    • Returns: void.

    Example:

    cache.set('user', { name: 'Alice' }, 60000); // Cache for 1 minute
  2. get<T>(key: string): T | null

    • Description: Retrieves a value from the cache.
    • Parameters:
      • key (string): The unique identifier for the cache entry.
    • Returns: The cached value or null if the key doesn't exist or is expired.

    Example:

    const user = cache.get<{ name: string }>('user');
  3. clear(): void

    • Description: Removes all entries from the cache.
    • Returns: void.

    Example:

    cache.clear();

Examples

Caching an API Response

TypeScript

import ApiResponseCache from 'api-response-cache';

const cache = new ApiResponseCache();

async function fetchUserData() {
  const cachedData = cache.get('user-data');

  if (cachedData) {
    console.log('Using cached data:', cachedData);
    return cachedData;
  }

  console.log('Fetching data from API...');
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
  const data = await response.json();

  cache.set('user-data', data, 60000); // Cache for 1 minute
  return data;
}

fetchUserData();

JavaScript

const ApiResponseCache = require('api-response-cache');

const cache = new ApiResponseCache();

async function fetchUserData() {
  const cachedData = cache.get('user-data');

  if (cachedData) {
    console.log('Using cached data:', cachedData);
    return cachedData;
  }

  console.log('Fetching data from API...');
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
  const data = await response.json();

  cache.set('user-data', data, 60000); // Cache for 1 minute
  return data;
}

fetchUserData();

Best Practices

  • Use meaningful keys for your cache entries to avoid collisions.
  • Clear cache entries if their data becomes stale or irrelevant.
  • Be cautious about memory usage if caching a large amount of data.

License

This project has no license. UNLICENSED.