2.1.1 • Published 6 months ago

prisma-extension-redis v2.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

prisma-extension-redis

The prisma-extension-redis library is a comprehensive package that provides a unified solution for optimizing database access times, enhancing cache management, and offering versatile functions for efficient Redis/Dragonfly database maintenance.

šŸš€ If prisma-extension-redis proves helpful, consider giving it a star! ⭐ Star Me!

Installation

Using npm:
npm install prisma-extension-redis
Using yarn:
yarn add prisma-extension-redis
Using pnpm:
pnpm add prisma-extension-redis
Using bun:
bun add prisma-extension-redis

Initializtion of setup

import {PrismaClient} from '@prisma/client';
import {Redis} from 'ioredis';
import pino from 'pino';
import {
  getCacheKey,
  getCacheKeyPattern,
  PrismaExtensionRedis,
} from 'prisma-extension-redis';

// Create a Redis client
const redis = new Redis({
  host: env.REDIS_HOST_NAME, // Specify Redis host name
  port: env.REDIS_PORT, // Specify Redis port
});

// Create a pino logger instance for logging
const logger = pino();

Auto cache config

Auto-caching can be enabled for all read operations by default. Set auto to customize behavior or exclude specific models or operations.

const auto = {
  excludedModels: ['Post'], // Models to exclude from auto-caching
  excludedOperations: ['findFirst', 'count', 'findMany'], // Operations to exclude from auto-caching
  models: [
    {
      model: 'User',
      excludedOperations: [],
      ttl: 10, // Time-to-live for caching
      stale: 5, // Stale time for caching
    },
  ], // Models-specific cache configurations
  ttl: 1, // Default time-to-live for caching
};

Cache Client Config is required to enable auto-cache.

Cache Client Config

This configuration is required for enabling auto-cache and handling caching using cache: true or cache: false per Prisma query (refer use cases).

const cache = {
  ttl: 1, // Time-to-live for caching
  stale: 1, // Stale time for caching
  storage: {
    type: 'redis',
    options: {
      client: redis,
      invalidation: {referencesTTL: 60}, // Invalidation settings
      log: logger, // Logger for cache events
    },
  }, // Storage configuration for async-cache-dedupe
};

Create Prisma Extended Client

// Create a Prisma client instance
const prisma = new PrismaClient();

// Extend Prisma with prisma-extension-redis
const extendedPrisma = prisma.$extends(
  PrismaExtensionRedis({auto, cache, redis})
);

Use case 1: Default Auto-Caching Configuration

// Example: Query a user and cache the result when auto caching is enabled
extendedPrisma.user.findUnique({
  where: {id},
});

// Example: Query a user and cache the result by setting `cache: true` to toggle auto cache
extendedPrisma.user.findUnique({
  where: {id},
  cache: true, // Enable caching with default configuration
});

// Example: Exclude automatic caching for a specific operation
extendedPrisma.user.findFirst({
  where: {userId: id},
  cache: false, // Disable caching for this operation
});

Use case 2: Selective Caching with Custom Configuration

// Example: Query a user and cache the result - with custom configuration
extendedPrisma.user.findUnique({
  where: {id},
  cache: {ttl: 5, key: getCacheKey([{prisma: 'User'}, {userId: id}])},
});

Use case 3: Invalidation of Cached Data

// Example: Update a user and invalidate related cache keys
extendedPrisma.user.update({
  where: {id},
  data: {username},
  uncache: {
    uncacheKeys: [
      getCacheKey([{prisma: 'User'}, {userId: id}]),
      getCacheKeyPattern([{prisma: '*'}, {userId: id}]), // Pattern matching under a specific key, eg: prisma:*:userId:1234
      getCacheKeyPattern([{prisma: 'Post'}, {userId: id}, {glob: '*'}]), // Utilizing the key 'glob' to create a wildcard region, eg: prisma:post:userId:1234:*
    ], // Keys to be invalidated
    hasPattern: true, // Use wildcard pattern for key matching
  },
});

Custom cache invalidation is designed for custom caching (not auto-caching).

Dependencies

  • ioredis

Key Features

  • Automatic Query Result Caching: Easily cache Prisma query results in Redis with minimal configuration.
  • Selective Cache Invalidation: Invalidate specific Prisma queries to ensure accurate and up-to-date data retrieval.
  • Fine-grained Control: Configure caching and invalidation settings on a per-query basis for granular control over caching behavior.
  • Cache Invalidation Strategies: Implement cache invalidation strategies to ensure that cached data remains up-to-date.
  • Versatile Functions: Utilize general-purpose functions for efficient Redis/Dragonfly database maintenance.

Why use prisma-extension-redis?

  • Simplified Dependencies: Instead of managing multiple packages, you now only need prisma-extension-redis for all the features.
  • Enhanced Maintenance: Centralized updates and improvements for all functionalities, leading to easier maintenance.
  • Streamlined Codebase: Consolidate your codebase by eliminating redundant dependencies and optimizing performance.
  • Community Focus: Join the community around prisma-extension-redis for collective support and collaborative development.

Upgrade to prisma-extension-redis today to experience a more streamlined and efficient Redis caching solution.

1.2.0

8 months ago

2.1.1

7 months ago

1.1.0

8 months ago

3.1.0

6 months ago

4.0.0

7 months ago

3.0.0

7 months ago

2.1.0

7 months ago

2.0.0

7 months ago

1.0.0

10 months ago