1.1.0 • Published 4 months ago

prisma-extension-redis-auto-cache v1.1.0

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

prisma-extension-redis-auto-cache

A Prisma extension that automatically caches query results in Redis and handles cache invalidation intelligently.

Features

  • 🚀 Automatic caching of findUnique, findFirst, and findMany queries
  • 🔄 Automatic cache invalidation on create, update, delete, and upsert operations
  • ⚙️ Configurable cache TTL and model exclusions
  • 🔑 Intelligent cache key generation
  • 🐉 Support for Redis and Dragonfly
  • 🔍 Debug logging option
  • 🎯 TypeScript support
  • 🔌 Flexible Redis connection options (URL, config, or existing client)

Installation

npm install prisma-extension-redis-auto-cache
# or
yarn add prisma-extension-redis-auto-cache

Usage

Basic Usage with Redis URL

import { PrismaClient } from '@prisma/client'
import { withRedisCache } from 'prisma-extension-redis-auto-cache'

const prisma = new PrismaClient().$extends(
  withRedisCache({
    redis: {
      type: 'url',
      url: 'redis://localhost:6379',
      options: {
        password: 'optional-password'
      }
    },
    ttl: 300, // 5 minutes
    excludeModels: ['Log'], // Models to exclude from caching
    prefix: 'my-app', // Custom cache key prefix
    debug: true, // Enable debug logging
  })
)

Using Redis Connection Config

const prisma = new PrismaClient().$extends(
  withRedisCache({
    redis: {
      type: 'config',
      config: {
        host: 'localhost',
        port: 6379,
        password: 'optional-password',
        db: 0
      }
    }
  })
)

Using Existing Redis Client

import Redis from 'ioredis';

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

const prisma = new PrismaClient().$extends(
  withRedisCache({
    redis: {
      type: 'client',
      client: redisClient
    }
  })
)

Configuration Options

OptionTypeDefaultDescription
redisRedisConnectionRequiredRedis connection configuration (URL, config, or client)
ttlnumber300Time-to-live for cached items in seconds
excludeModelsstring[][]Array of model names to exclude from caching
prefixstring'prisma-cache'Prefix for cache keys
debugbooleanfalseEnable debug logging
keyGeneratorFunctionBuilt-inCustom function for generating cache keys

Redis Connection Types

The redis option accepts three types of configurations:

  1. URL with Options
{
  type: 'url',
  url: 'redis://localhost:6379',
  options?: RedisOptions // Optional ioredis options
}
  1. Connection Config
{
  type: 'config',
  config: RedisOptions // ioredis connection options
}
  1. Existing Client
{
  type: 'client',
  client: Redis // Existing ioredis instance
}

Custom Key Generator

You can provide a custom key generator function to control how cache keys are generated:

const prisma = new PrismaClient().$extends(
  withRedisCache({
    redis: { type: 'url', url: 'redis://localhost:6379' },
    keyGenerator: (model: string, operation: string, args: any) => {
      return `custom:${model}:${operation}:${JSON.stringify(args)}`
    }
  })
)

How It Works

  1. Query Caching: When a findUnique, findFirst, or findMany operation is performed, the extension:

    • Generates a unique cache key based on the model, operation, and query arguments
    • Checks if the result exists in Redis
    • If found, returns the cached result
    • If not found, executes the query and caches the result
  2. Cache Invalidation: When a create, update, delete, or upsert operation is performed:

    • All cached entries for the affected model are invalidated
    • This ensures data consistency while maintaining simplicity
  3. Metadata Storage: The extension maintains metadata about cached items using Redis sets and hashes, enabling efficient invalidation and monitoring.

Best Practices

  1. Model Exclusion: Consider excluding frequently changing models or models with sensitive data from caching.

  2. TTL Configuration: Set an appropriate TTL based on your data's update frequency and consistency requirements.

  3. Redis Configuration: For production, configure Redis with appropriate persistence and memory settings.

  4. Client Management: When using an existing Redis client, make sure to manage its lifecycle appropriately.

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.