prisma-extension-redis-auto-cache v1.1.0
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
, andfindMany
queries - 🔄 Automatic cache invalidation on
create
,update
,delete
, andupsert
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
Option | Type | Default | Description |
---|---|---|---|
redis | RedisConnection | Required | Redis connection configuration (URL, config, or client) |
ttl | number | 300 | Time-to-live for cached items in seconds |
excludeModels | string[] | [] | Array of model names to exclude from caching |
prefix | string | 'prisma-cache' | Prefix for cache keys |
debug | boolean | false | Enable debug logging |
keyGenerator | Function | Built-in | Custom function for generating cache keys |
Redis Connection Types
The redis
option accepts three types of configurations:
- URL with Options
{
type: 'url',
url: 'redis://localhost:6379',
options?: RedisOptions // Optional ioredis options
}
- Connection Config
{
type: 'config',
config: RedisOptions // ioredis connection options
}
- 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
Query Caching: When a
findUnique
,findFirst
, orfindMany
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
Cache Invalidation: When a
create
,update
,delete
, orupsert
operation is performed:- All cached entries for the affected model are invalidated
- This ensures data consistency while maintaining simplicity
Metadata Storage: The extension maintains metadata about cached items using Redis sets and hashes, enabling efficient invalidation and monitoring.
Best Practices
Model Exclusion: Consider excluding frequently changing models or models with sensitive data from caching.
TTL Configuration: Set an appropriate TTL based on your data's update frequency and consistency requirements.
Redis Configuration: For production, configure Redis with appropriate persistence and memory settings.
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.