{"id":23301426,"url":"https://github.com/yxx4c/prisma-redis-extension","last_synced_at":"2025-07-14T15:36:56.754Z","repository":{"id":217752273,"uuid":"744703325","full_name":"yxx4c/prisma-extension-redis","owner":"yxx4c","description":"Extensive Prisma extension designed for efficient caching and cache invalidation using Redis and Dragonfly Databases","archived":false,"fork":false,"pushed_at":"2024-12-03T08:29:59.000Z","size":434,"stargazers_count":76,"open_issues_count":8,"forks_count":5,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-23T07:50:15.113Z","etag":null,"topics":["cache","cache-invalidation","prisma-extension","prisma-orm","redis"],"latest_commit_sha":null,"homepage":"https://npmjs.com/prisma-extension-redis","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yxx4c.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-17T20:48:55.000Z","updated_at":"2025-06-19T18:35:36.000Z","dependencies_parsed_at":"2024-11-15T18:20:53.562Z","dependency_job_id":"3e14fa34-1bef-4179-a8f9-4c135ec37009","html_url":"https://github.com/yxx4c/prisma-extension-redis","commit_stats":{"total_commits":76,"total_committers":1,"mean_commits":76.0,"dds":0.0,"last_synced_commit":"73cfda4a08258fbc2912ee505f1105e92c4fb019"},"previous_names":["yxx4c/prisma-redis-extension","yxx4c/prisma-extension-redis"],"tags_count":5,"template":false,"template_full_name":null,"purl":"pkg:github/yxx4c/prisma-extension-redis","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxx4c%2Fprisma-extension-redis","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxx4c%2Fprisma-extension-redis/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxx4c%2Fprisma-extension-redis/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxx4c%2Fprisma-extension-redis/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yxx4c","download_url":"https://codeload.github.com/yxx4c/prisma-extension-redis/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxx4c%2Fprisma-extension-redis/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265313054,"owners_count":23745185,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","cache-invalidation","prisma-extension","prisma-orm","redis"],"created_at":"2024-12-20T10:12:26.299Z","updated_at":"2025-07-14T15:36:56.734Z","avatar_url":"https://github.com/yxx4c.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n# Prisma Extension Redis\n\n[![test](https://github.com/yxx4c/prisma-extension-redis/actions/workflows/test.yml/badge.svg)](https://github.com/yxx4c/prisma-extension-redis/actions/workflows/test.yml)\n[![codecov](https://codecov.io/github/yxx4c/prisma-extension-redis/graph/badge.svg?token=G7O92H6I7T)](https://codecov.io/github/yxx4c/prisma-extension-redis)\n![NPM License](https://img.shields.io/npm/l/prisma-extension-redis)\n![NPM Version (latest)](https://img.shields.io/npm/v/prisma-extension-redis/latest)\n![NPM Version (next)](https://img.shields.io/npm/v/prisma-extension-redis/next)\n![NPM Downloads](https://img.shields.io/npm/dw/prisma-extension-redis)\n\n`prisma-extension-redis` provides seamless integration with Prisma and Redis/Dragonfly databases, offering efficient caching mechanisms to improve data access times and overall application performance.\n\n🚀 If `prisma-extension-redis` proves helpful, consider giving it a star! [⭐ Star Me!](https://github.com/yxx4c/prisma-extension-redis)\n\n---\n\n## Installation\n\nYou can install `prisma-extension-redis` using your preferred package manager:\n\n**Using npm:**\n\n```bash\nnpm install prisma-extension-redis\n```\n\n**Using yarn:**\n\n```bash\nyarn add prisma-extension-redis\n```\n\n**Using pnpm:**\n\n```bash\npnpm add prisma-extension-redis\n```\n\n**Using bun:**\n\n```bash\nbun add prisma-extension-redis\n```\n\n---\n\n## Setup and Configuration\n\n### Step 1: Initialize Required Clients\n\nBefore setting up caching, initialize your Prisma client, Redis client config, and logger:\n\n```javascript\nimport pino from 'pino';\nimport { PrismaClient } from '@prisma/client';\nimport { Redis } from 'iovalkey';\nimport {SuperJSON} from 'superjson';\n\nimport {\n  CacheCase,\n  PrismaExtensionRedis,\n  type AutoCacheConfig,\n  type CacheConfig,\n} from 'prisma-extension-redis';\n\n\n// Prisma Client\nconst prisma = new PrismaClient();\n\n// Redis client config\nconst client = {\n  host: process.env.REDIS_HOST_NAME, // Redis host\n  port: process.env.REDIS_PORT,      // Redis port\n};\n\n// Create a logger using pino (optional)\nconst logger = pino();\n```\n\n### Step 2: Configure Auto-Cache Settings\n\n`auto` settings enable automated caching for read operations with flexible customization.\n\n#### Example Auto-Cache Configuration\n\n```javascript\nconst auto: AutoCacheConfig = {\n  excludedModels: ['Post'], // Models excluded from auto-caching\n  excludedOperations: ['findFirst', 'count', 'findMany'], // Operations excluded from auto-caching\n  models: [\n    {\n      model: 'User', // Model-specific auto-cache settings\n      excludedOperations: ['count'], // Operations to exclude\n      ttl: 10,  // Time-to-live (TTL) for cache in seconds\n      stale: 5, // Stale time in seconds\n    },\n  ],\n  ttl: 30, // Default TTL for cache in seconds\n};\n```\n\n**Note**:\n\n 1. Excluded operations and models will not benefit from auto-caching.\n 2. Use `ttl` and `stale` values to define caching duration.\n\n### Step 3: Configure Cache Client\n\nThe cache client configuration is necessary to enable caching, either automatically or manually.\n\n#### Example Cache Configuration\n\n```javascript\nconst config: CacheConfig = {\n ttl: 60, // Default Time-to-live for caching in seconds\n  stale: 30, // Default Stale time after ttl in seconds\n  auto, // Auto-caching options (configured above)\n  logger, // Logger for cache events (configured above)\n  transformer: {\n    // Custom serialize and deserialize function for additional functionality if required\n    deserialize: data =\u003e SuperJSON.parse(data),\n    serialize: data =\u003e SuperJSON.stringify(data),\n  },\n  type: 'JSON', // Redis cache type, whether you prefer the data to be stored as JSON or STRING in Redis\n  cacheKey: { // Inbuilt cache key configuration\n    case: CacheCase.SNAKE_CASE, // Select a cache case conversion option for generated keys from CacheCase\n    delimiter: '*', // Delimiter for keys (default value: ':')\n    prefix: 'awesomeness', // Cache key prefix (default value: 'prisma')\n  },\n};\n```\n\n**Note**: Cache case conversion strips all non alpha numeric characters\n\n### Step 4: Extend Prisma Client\n\nNow, extend your Prisma client with caching capabilities using `prisma-extension-redis`:\n\n```javascript\nconst extendedPrisma = prisma.$extends(\n  PrismaExtensionRedis({ config, client })\n);\n```\n\n---\n\n## Usage Guide\n\n### Automatic Caching\n\nWith auto-caching, read operations (e.g., `findUnique`, `findMany`) are cached automatically based on the defined configuration.\n\n**Basic Example:**\n\n```javascript\n// Cached automatically based on auto-cache settings\nextendedPrisma.user.findUnique({\n  where: { id: userId },\n});\n\n// Manually enable cache for a query\nextendedPrisma.user.findUnique({\n  where: { id: userId },\n  cache: true, // Toggle caching on\n});\n\n// Disable cache for specific query\nextendedPrisma.user.findFirst({\n  where: { id: userId },\n  cache: false, // Toggle caching off\n});\n```\n\n**Note**:\n\n1. If `auto-cache` is set to `false` and `cache` is set to `true` for the query, the default values from the cache configuration will be applied.\n2. If `cache` is set to `false` and `auto-cache` is set to `true`, the query will not be cached.\n\n### Custom Caching with `getKey`\n\nFor greater control over caching, generate custom cache keys and TTL settings.\n\n**Example with Custom Cache Key:**\n\n```javascript\nconst customKey = extendedPrisma.getKey({ params: [{ prisma: 'User' }, { id: userId }] });\n\nextendedPrisma.user.findUnique({\n  where: { id: userId },\n  cache: { ttl: 5, key: customKey }, // Custom TTL and cache key\n});\n```\n\n### Cache Invalidation\n\nCache invalidation ensures data consistency by removing or updating cached data when changes occur in the database.\n\n**Example of Cache Invalidation:**\n\n```javascript\n// Invalidate cache when updating a user's information\nextendedPrisma.user.update({\n  where: { id: userId },\n  data: { username: newUsername },\n  uncache: {\n    uncacheKeys: [\n      extendedPrisma.getKey({ params: [{ prisma: 'User' }, { id: userId }] }), // Specific key to invalidate\n      extendedPrisma.getKeyPattern({ params: [{ prisma: '*' }, { id: userId }]}), // Pattern for wildcard invalidation\n      extendedPrisma.getKeyPattern({ params: [{ prisma: 'Post' }, { id: userId }, { glob: '*' }]}), // Use glob for more complex patterns\n    ],\n    hasPattern: true, // Use pattern matching for invalidation\n  },\n});\n```\n\n**Explanation of Cache Invalidation:**\n\n- **`uncacheKeys`**: Specifies the keys or patterns to be invalidated.\n- **`hasPattern`**: Indicates if wildcard patterns are used for key matching.\n\n---\n\n## Key Concepts Explained\n\n### 1. **Time-to-Live (TTL)**\n\n- Specifies how long (in seconds) a cached entry should remain before expiring.\n- **Default TTL**: Used when no specific TTL is provided for a query.\n\n### 2. **Stale Time**\n\n- After the TTL expires, stale time defines how long expired data can still be used while refreshing data in the background.\n- This ensures that users experience minimal latency even when data is being updated.\n\n### 3. **Cache Key Management**\n\n- **`getKey`**: Generates a unique key for caching queries from provided key context parameters.\n- **`getAutoKey`**: Generates a unique key for auto-caching queries, based on query parameters.\n- **`getKeyPattern`**: Creates patterns for more complex invalidation scenarios, using wildcards.\n\n---\n\n## Key Features\n\n- **Auto-Caching**: Automatically cache read operations, reducing redundant queries and improving performance.\n- **Selective Caching**: Customize which queries to cache, how long to cache them, and whether to cache them at all.\n- **Efficient Invalidation**: Keep cached data up-to-date by selectively invalidating caches when updates or deletions occur.\n- **Granular Control**: Easily toggle caching on or off for individual queries as needed.\n- **Logger Support**: Integrate logging to monitor cache hits, misses, and invalidations for easier debugging and optimization.\n\n---\n\n## Prerequisites\n\n- Ensure you have a running Redis or Dragonfly instance. If using Redis, `Redis.JSON` must be enabled to use JSON type cache (by default, it is enabled in Dragonfly).\n\n## Dependencies\n\n- `iovalkey` package is used for Redis connectivity.\n- `micromatch` is used for patter matching for keys.\n- `object-code` is used for generating unique hash in auto-caching keys.\n- `lodash-es` is used for CacheCase logic in key management.\n\n---\n\n## Final Thoughts\n\n`prisma-extension-redis` offers an efficient and powerful way to manage caching in Prisma-based applications. By leveraging both automatic and custom caching, you can optimize your application's performance while maintaining data consistency.\n\nUpgrade to `prisma-extension-redis` for an optimized caching strategy and contribute to its growth by starring the repository if you find it useful!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyxx4c%2Fprisma-redis-extension","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyxx4c%2Fprisma-redis-extension","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyxx4c%2Fprisma-redis-extension/lists"}