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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@natiwo/cache

v0.1.0

Published

Redis caching with decorators and utilities

Readme

@natiwo/cache

Advanced caching with decorators and Redis

npm version

Installation

pnpm add @natiwo/cache ioredis

Features

  • 🎯 Method Decorators - @Cacheable, @CacheInvalidate, @CachePut
  • Redis Backend - Fast distributed caching
  • 🔄 Auto-invalidation - Smart cache management
  • ⏱️ TTL Support - Flexible expiration
  • 🔧 Custom Key Generation - Full control over cache keys

Quick Start

Basic Caching

import { Cacheable, CacheInvalidate, getCacheManager } from '@natiwo/cache';

class UserService {
  @Cacheable({ ttl: 600, prefix: 'user' })
  async getUser(id: string) {
    return await db.user.findUnique({ where: { id } });
  }

  @CacheInvalidate({
    keys: (id: string) => [`user:getUser:${id}`]
  })
  async updateUser(id: string, data: UpdateUserInput) {
    return await db.user.update({ where: { id }, data });
  }

  @CachePut({ ttl: 600, prefix: 'user' })
  async createUser(data: CreateUserInput) {
    return await db.user.create({ data });
  }
}

Manual Cache Operations

const cache = getCacheManager();

// Set with TTL
await cache.set('key', { data: 'value' }, { ttl: 300 });

// Get
const value = await cache.get('key');

// Delete
await cache.delete('key');

// Delete by pattern
await cache.deletePattern('user:*');

// Remember pattern
const user = await cache.remember(
  `user:${id}`,
  async () => await db.user.findUnique({ where: { id } }),
  { ttl: 600 }
);

Decorators

@Cacheable

Caches method result automatically.

@Cacheable({
  ttl?: number;              // Time to live in seconds
  prefix?: string;           // Cache key prefix
  keyGenerator?: (...args) => string;  // Custom key function
  condition?: (...args) => boolean;    // Cache condition
})

Example:

class ProductService {
  @Cacheable({ 
    ttl: 3600,
    prefix: 'product',
    condition: (id: string) => id !== 'admin'
  })
  async getProduct(id: string) {
    return await db.product.findUnique({ where: { id } });
  }
}

@CacheInvalidate

Invalidates cache on method execution.

@CacheInvalidate({
  keys?: string[] | ((...args) => string[]);
  pattern?: string | ((...args) => string);
  when?: 'before' | 'after';  // Default: 'after'
})

Example:

class PostService {
  @CacheInvalidate({
    keys: (id: string) => [`post:${id}`, 'posts:all'],
    when: 'after'
  })
  async deletePost(id: string) {
    return await db.post.delete({ where: { id } });
  }

  @CacheInvalidate({
    pattern: 'posts:*'
  })
  async createPost(data: CreatePostInput) {
    return await db.post.create({ data });
  }
}

@CachePut

Always executes method and updates cache.

@CachePut({
  ttl?: number;
  prefix?: string;
  keyGenerator?: (...args) => string;
})

Example:

class OrderService {
  @CachePut({ ttl: 1800, prefix: 'order' })
  async processOrder(orderId: string) {
    const order = await db.order.update({
      where: { id: orderId },
      data: { status: 'PROCESSED' },
    });
    return order;
  }
}

Advanced Usage

Custom Key Generator

class UserService {
  @Cacheable({
    ttl: 600,
    keyGenerator: (email: string, includeProfile: boolean) => {
      return `user:${email}:${includeProfile ? 'full' : 'basic'}`;
    }
  })
  async getUserByEmail(email: string, includeProfile: boolean = false) {
    return await db.user.findUnique({
      where: { email },
      include: { profile: includeProfile },
    });
  }
}

Conditional Caching

@Cacheable({
  ttl: 600,
  condition: (userId: string, role: string) => {
    // Don't cache for admins
    return role !== 'admin';
  }
})
async getPermissions(userId: string, role: string) {
  return await db.permission.findMany({ where: { userId } });
}

Multi-level Invalidation

@CacheInvalidate({
  keys: (productId: string) => [
    `product:${productId}`,
    `product:${productId}:details`,
    `product:${productId}:reviews`,
  ],
  pattern: 'products:list:*',
})
async updateProduct(productId: string, data: UpdateProductInput) {
  return await db.product.update({
    where: { id: productId },
    data,
  });
}

Configuration

REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your-password
REDIS_DB=0

Or programmatic:

import { getCacheManager } from '@natiwo/cache';
import Redis from 'ioredis';

const redis = new Redis({
  host: 'localhost',
  port: 6379,
});

const cache = getCacheManager(redis);

Best Practices

  1. Use appropriate TTLs

    // Frequently changing data - short TTL
    @Cacheable({ ttl: 60 })
    async getActiveUsers() { ... }
       
    // Rarely changing data - longer TTL
    @Cacheable({ ttl: 3600 })
    async getCountries() { ... }
  2. Invalidate strategically

    // Invalidate related caches
    @CacheInvalidate({
      keys: (userId) => [
        `user:${userId}`,
        `user:${userId}:profile`,
        `user:${userId}:settings`,
      ]
    })
    async updateUser(userId: string, data: any) { ... }
  3. Use patterns for bulk invalidation

    @CacheInvalidate({ pattern: 'products:*' })
    async importProducts(products: any[]) { ... }
  4. Monitor cache hit rates

    const stats = await cache.info();
    console.log(`Hit rate: ${stats.hitRate}%`);

License

MIT © NATIWO Sistemas