### AdonisJS Cache Driver Configuration Examples Source: https://context7.com/adonisjs/cache/llms.txt Configure different cache drivers like memory, Redis, database, file, DynamoDB, Kysely, and Orchid. Each driver has specific backend options and integration points. ```typescript import { drivers } from '@adonisjs/cache' import app from '@adonisjs/core/services/app' import env from '#start/env' // Memory driver (L1) - fast in-process caching const memoryL1 = drivers.memory({ maxSize: 1000, maxItems: 500, }) // Redis driver (L2) - uses @adonisjs/redis connection const redisL2 = drivers.redis({ connectionName: 'main', prefix: 'cache', }) // Database driver (L2) - uses @adonisjs/lucid connection const databaseL2 = drivers.database({ connectionName: 'primary', tableName: 'cache', autoCreateTable: true, pruneInterval: 60000, }) // File driver (L2) - stores cache in filesystem const fileL2 = drivers.file({ directory: app.tmpPath('cache'), }) // DynamoDB driver (L2) - AWS DynamoDB backend const dynamoL2 = drivers.dynamodb({ table: { name: 'cache' }, credentials: { accessKeyId: env.get('AWS_ACCESS_KEY_ID'), secretAccessKey: env.get('AWS_SECRET_ACCESS_KEY'), }, region: env.get('AWS_REGION'), endpoint: env.get('DYNAMODB_ENDPOINT'), }) // Redis bus for L1 synchronization across instances const redisBus = drivers.redisBus({ connectionName: 'main', retryQueue: { enabled: true, maxSize: 1000 }, }) // Kysely driver (L2) - for Kysely ORM users const kyselyL2 = drivers.kysely({ connection: kyselyInstance, tableName: 'cache', }) // Orchid driver (L2) - for Orchid ORM users const orchidL2 = drivers.orchid({ connection: orchidInstance, tableName: 'cache', }) ``` -------------------------------- ### AdonisJS Cache Service Basic Operations Source: https://context7.com/adonisjs/cache/llms.txt Perform basic cache operations like setting, getting, and checking for key existence. Supports async/await and provides default values. ```typescript // Import cache service singleton import cache from '@adonisjs/cache/services/main' // Or inject via container const cache = await app.container.make('cache.manager') // Basic get/set operations await cache.set({ key: 'user:123', value: { name: 'John', email: 'john@example.com' } }) const user = await cache.get({ key: 'user:123' }) // Returns: { name: 'John', email: 'john@example.com' } // Set with TTL await cache.set({ key: 'session:abc', value: { userId: 123 }, ttl: '30m' }) // Get with default value const settings = await cache.get({ key: 'settings', defaultValue: { theme: 'dark' } }) // Check if key exists const exists = await cache.has({ key: 'user:123' }) // Delete specific key await cache.delete({ key: 'user:123' }) // Clear entire cache await cache.clear() ``` -------------------------------- ### Cache Service API Source: https://context7.com/adonisjs/cache/llms.txt Methods for getting, setting, and managing cached data using the main cache service. ```APIDOC ## Cache Service API The cache service provides methods for getting, setting, and managing cached data. Access it via dependency injection or the service import. All operations support async/await patterns. ### Basic Get/Set ```typescript // Import cache service singleton import cache from '@adonisjs/cache/services/main' // Or inject via container // const cache = await app.container.make('cache.manager') await cache.set({ key: 'user:123', value: { name: 'John', email: 'john@example.com' } }) const user = await cache.get({ key: 'user:123' }) // Returns: { name: 'John', email: 'john@example.com' } ``` ### Set with TTL Set a cache entry with a specific time-to-live. ```typescript await cache.set({ key: 'session:abc', value: { userId: 123 }, ttl: '30m' }) ``` ### Get with Default Value Retrieve a value, providing a default if the key does not exist. ```typescript const settings = await cache.get({ key: 'settings', defaultValue: { theme: 'dark' } }) ``` ### Get or Set (Cache-Aside) Retrieve a value, or compute and store it if it's not found. ```typescript const products = await cache.getOrSet({ key: 'products:featured', ttl: '1h', factory: async () => { // Expensive operation - only called on cache miss return await Product.query().where('featured', true).exec() }, }) ``` ### Check if Key Exists Determine if a cache key is present. ```typescript const exists = await cache.has({ key: 'user:123' }) ``` ### Delete Key Remove a specific cache entry. ```typescript await cache.delete({ key: 'user:123' }) ``` ### Clear Cache Remove all entries from the cache. ```typescript await cache.clear() ``` ### Use Specific Store Access a cache store by its name. ```typescript const memoryCache = cache.use('memoryOnly') await memoryCache.set({ key: 'temp', value: 'data' }) ``` ### Namespaces Organize cache keys into logical groups. ```typescript const userCache = cache.namespace('users') await userCache.set({ key: '123', value: { name: 'John' } }) // Key becomes 'users:123' await userCache.clear() // Only clears 'users:*' keys ``` ### Tag-Based Caching Associate tags with cache entries for bulk invalidation. ```typescript await cache.set({ key: 'post:1', value: postData, tags: ['posts', 'user:1'], }) await cache.set({ key: 'post:2', value: postData2, tags: ['posts', 'user:2'], }) // Invalidate all posts by user 1 await cache.deleteByTag({ tags: ['user:1'] }) ``` ### Prune Expired Entries Manually remove expired entries (useful for drivers without native TTL support). ```typescript await cache.use('database').prune() ``` ### Disconnect Stores Gracefully disconnect all active cache stores, typically on application shutdown. ```typescript await cache.disconnectAll() ``` ``` -------------------------------- ### AdonisJS Cache Service Get or Set Pattern Source: https://context7.com/adonisjs/cache/llms.txt Implement the cache-aside pattern using `getOrSet`. This is useful for expensive operations that should only be executed on a cache miss. ```typescript // Get or set pattern (cache-aside) const products = await cache.getOrSet({ key: 'products:featured', ttl: '1h', factory: async () => { // Expensive operation - only called on cache miss return await Product.query().where('featured', true).exec() }, }) ``` -------------------------------- ### AdonisJS Cache Service Store and Namespace Usage Source: https://context7.com/adonisjs/cache/llms.txt Demonstrates how to use a specific cache store and how to organize cache keys using namespaces for logical grouping. ```typescript // Use a specific store const memoryCache = cache.use('memoryOnly') await memoryCache.set({ key: 'temp', value: 'data' }) // Using namespaces for logical grouping const userCache = cache.namespace('users') await userCache.set({ key: '123', value: { name: 'John' } }) // Key becomes 'users:123' await userCache.clear() // Only clears 'users:*' keys ``` -------------------------------- ### Define Cache Configuration with defineConfig Source: https://context7.com/adonisjs/cache/llms.txt Use defineConfig to create a typed cache configuration object. Specify the default store, global settings like TTL and grace period, and define individual stores with their respective drivers and configurations. ```typescript // config/cache.ts import app from '@adonisjs/core/services/app' import { defineConfig, store, drivers } from '@adonisjs/cache' const cacheConfig = defineConfig({ default: 'redis', // Optional global settings ttl: '30m', gracePeriod: { enabled: true, duration: '6h', }, stores: { // Memory-only store for fast, ephemeral caching memoryOnly: store().useL1Layer(drivers.memory({ maxSize: 1000 })), // Redis store with memory L1 layer redis: store() .useL1Layer(drivers.memory({ maxSize: 500 })) .useL2Layer(drivers.redis({ connectionName: 'main' })), // Database store with memory L1 layer database: store() .useL1Layer(drivers.memory()) .useL2Layer(drivers.database({ connectionName: 'primary', tableName: 'cache', autoCreateTable: true, })), // File-based store file: store() .useL1Layer(drivers.memory()) .useL2Layer(drivers.file({ directory: app.tmpPath('cache') })), } }) export default cacheConfig // Type inference for cache stores declare module '@adonisjs/cache/types' { interface CacheStores extends InferStores {} } ``` -------------------------------- ### Cache Drivers Configuration Source: https://context7.com/adonisjs/cache/llms.txt Factory functions for creating instances of various cache drivers, each with specific configuration options. ```APIDOC ## Cache Drivers The `drivers` object provides factory functions for all supported cache drivers. Each driver is configured with backend-specific options and integrates with AdonisJS services where applicable. ### Memory Driver (L1) Fast in-process caching. ```typescript const memoryL1 = drivers.memory({ maxSize: 1000, maxItems: 500, }) ``` ### Redis Driver (L2) Uses `@adonisjs/redis` connection. ```typescript const redisL2 = drivers.redis({ connectionName: 'main', prefix: 'cache', }) ``` ### Database Driver (L2) Uses `@adonisjs/lucid` connection. ```typescript const databaseL2 = drivers.database({ connectionName: 'primary', tableName: 'cache', autoCreateTable: true, pruneInterval: 60000, }) ``` ### File Driver (L2) Stores cache in the filesystem. ```typescript const fileL2 = drivers.file({ directory: app.tmpPath('cache'), }) ``` ### DynamoDB Driver (L2) AWS DynamoDB backend. ```typescript const dynamoL2 = drivers.dynamodb({ table: { name: 'cache' }, credentials: { accessKeyId: env.get('AWS_ACCESS_KEY_ID'), secretAccessKey: env.get('AWS_SECRET_ACCESS_KEY'), }, region: env.get('AWS_REGION'), endpoint: env.get('DYNAMODB_ENDPOINT'), }) ``` ### Redis Bus for L1 Synchronization For synchronizing L1 cache across multiple instances. ```typescript const redisBus = drivers.redisBus({ connectionName: 'main', retryQueue: { enabled: true, maxSize: 1000 }, }) ``` ### Kysely Driver (L2) For Kysely ORM users. ```typescript const kyselyL2 = drivers.kysely({ connection: kyselyInstance, tableName: 'cache', }) ``` ### Orchid Driver (L2) For Orchid ORM users. ```typescript const orchidL2 = drivers.orchid({ connection: orchidInstance, tableName: 'cache', }) ``` ``` -------------------------------- ### Create Cache Stores with the store Function Source: https://context7.com/adonisjs/cache/llms.txt The store function builds cache stores using a fluent API. Configure L1/L2 layers, bus synchronization, and custom options like prefix, TTL, and grace period. ```typescript import { store, drivers } from '@adonisjs/cache' // Simple memory-only store const memoryStore = store().useL1Layer(drivers.memory()) // Two-layer store with Redis backend const redisStore = store({ prefix: 'app' }) .useL1Layer(drivers.memory({ maxSize: 1000 })) .useL2Layer(drivers.redis({ connectionName: 'main' })) // Multi-instance setup with Redis bus for L1 synchronization const distributedStore = store({ prefix: 'distributed' }) .useL1Layer(drivers.memory({ maxSize: 500 })) .useL2Layer(drivers.redis({ connectionName: 'main' })) .useBus(drivers.redisBus({ connectionName: 'main' })) // Store with custom options const customStore = store({ prefix: 'custom', ttl: '1h', gracePeriod: { enabled: true, duration: '2h' }, }) .useL1Layer(drivers.memory()) .useL2Layer(drivers.database({ tableName: 'custom_cache' })) ``` -------------------------------- ### Cache User List with Namespace and Tags Source: https://context7.com/adonisjs/cache/llms.txt Cache a list of users using `cache.namespace` for organization and `tags` for easier invalidation. The `getOrSet` pattern is used with a factory function to fetch data. ```typescript async index({ response }: HttpContext) { const users = await cache.namespace('users').getOrSet({ key: 'all', ttl: '5m', tags: ['user-list'], factory: async () => { return await User.query().orderBy('created_at', 'desc').limit(100) }, }) return response.json(users) } ``` -------------------------------- ### Clear Cache with Ace Command Source: https://context7.com/adonisjs/cache/llms.txt Use the `cache:clear` Ace command to clear the application cache. Supports clearing specific stores, namespaces, or tags, and includes a `--force` option to skip confirmation in production. ```bash # Clear default cache store node ace cache:clear ``` ```bash # Clear specific store node ace cache:clear redis ``` ```bash # Clear specific namespace node ace cache:clear --namespace=users node ace cache:clear -n users ``` ```bash # Invalidate specific tags node ace cache:clear --tags=posts --tags=comments node ace cache:clear -t posts -t comments ``` ```bash # Force clear in production (skip confirmation) node ace cache:clear --force ``` ```bash # Combine store and namespace node ace cache:clear redis --namespace=sessions ``` -------------------------------- ### Cache User Data in Controller Source: https://context7.com/adonisjs/cache/llms.txt Use `cache.getOrSet` in controllers to cache request-level data like user profiles. Specify a key, TTL, and a factory function to fetch and store data if it's not already in the cache. ```typescript import type { HttpContext } from '@adonisjs/core/http' import cache from '@adonisjs/cache/services/main' import User from '#models/user' export default class UsersController { async show({ params, response }: HttpContext) { const user = await cache.getOrSet({ key: `user:${params.id}`, ttl: '10m', factory: async () => { return await User.query() .where('id', params.id) .preload('profile') .firstOrFail() }, }) return response.json(user) } ``` -------------------------------- ### Delete Cache Entry with Ace Command Source: https://context7.com/adonisjs/cache/llms.txt Use the `cache:delete` Ace command to remove a specific cache entry by its key. Includes production confirmation prompts for safety. ```bash # Delete a specific key from default store node ace cache:delete user:123 ``` ```bash # Delete from specific store node ace cache:delete session:abc redis ``` ```bash # Example output # ✔ Deleted cache key "user:123" from "redis" cache successfully # If key not found # ⚠ Cache key "user:123" not found in "redis" cache ``` -------------------------------- ### Prune Expired Cache Entries with Ace Command Source: https://context7.com/adonisjs/cache/llms.txt Use the `cache:prune` Ace command to remove expired cache entries. This is particularly useful for drivers like Database or File that may not have native TTL support. ```bash # Prune default store node ace cache:prune ``` ```bash # Prune specific store node ace cache:prune database ``` ```bash # Prune file-based cache node ace cache:prune file ``` ```bash # Example output # ✔ Pruned expired entries from "database" cache successfully ``` -------------------------------- ### Listen to Cache Events Source: https://context7.com/adonisjs/cache/llms.txt Listen to cache events such as 'cache:hit', 'cache:miss', 'cache:written', 'cache:deleted', and 'cache:cleared' using the AdonisJS emitter. Also includes listeners for bus messages used in distributed cache synchronization. ```typescript import emitter from '@adonisjs/core/services/emitter' // Cache hit event emitter.on('cache:hit', (event) => { console.log(`Cache hit: ${event.key} from store ${event.store}`) // event: { key: string, value: any, store: string } }) // Cache miss event emitter.on('cache:miss', (event) => { console.log(`Cache miss: ${event.key}`) // event: { key: string, store: string } }) // Cache written event emitter.on('cache:written', (event) => { console.log(`Cache written: ${event.key}`) // event: { key: string, value: any, store: string } }) // Cache deleted event emitter.on('cache:deleted', (event) => { console.log(`Cache deleted: ${event.key}`) // event: { key: string, store: string } }) // Cache cleared event emitter.on('cache:cleared', (event) => { console.log(`Cache cleared: store ${event.store}`) // event: { store: string } }) // Bus message events (for distributed cache synchronization) emitter.on('bus:message:published', (event) => { console.log('Bus message published:', event) }) emitter.on('bus:message:received', (event) => { console.log('Bus message received:', event) }) ``` -------------------------------- ### Access Cache in Edge.js Templates Source: https://context7.com/adonisjs/cache/llms.txt Access the cache manager as a global helper within Edge.js templates to retrieve, set, or get-and-set cached data. Supports specifying a cache store. ```edge {{-- Access cache in Edge templates --}} @set('cachedUser', await cache.get({ key: 'user:' + userId })) @if(cachedUser)

Welcome back, {{ cachedUser.name }}!

@else

Loading user data...

@endif {{-- Use getOrSet for view-level caching --}} @set('stats', await cache.getOrSet({ key: 'dashboard:stats', ttl: '5m', factory: async () => { return await Stats.getDashboardData() } }))
Users: {{ stats.userCount }} Posts: {{ stats.postCount }}
{{-- Use specific store --}} @set('settings', await cache.use('memoryOnly').get({ key: 'app:settings' })) ``` -------------------------------- ### Invalidate and Update Cache After User Update Source: https://context7.com/adonisjs/cache/llms.txt After updating a user, invalidate the existing cache entry using `cache.delete` and then update the cache with the new data using `cache.set`. This ensures consistency. ```typescript // Invalidate cache after update await cache.delete({ key: `user:${params.id}` }) // Or update cache with new data await cache.set({ key: `user:${params.id}`, value: user.serialize(), ttl: '10m', }) return response.json(user) } ``` -------------------------------- ### AdonisJS Cache Service Pruning and Disconnection Source: https://context7.com/adonisjs/cache/llms.txt Manually prune expired entries for drivers that do not support native TTL expiration and disconnect all cache stores when the application shuts down. ```typescript // Prune expired entries (for drivers without native TTL) await cache.use('database').prune() // Disconnect all stores on shutdown await cache.disconnectAll() ``` -------------------------------- ### AdonisJS Cache Service Tag-Based Caching Source: https://context7.com/adonisjs/cache/llms.txt Utilize tag-based caching to invalidate related cache entries. This allows for more granular cache management, especially when dealing with collections of data. ```typescript // Tag-based caching await cache.set({ key: 'post:1', value: postData, tags: ['posts', 'user:1'], }) await cache.set({ key: 'post:2', value: postData2, tags: ['posts', 'user:2'], }) // Invalidate all posts by user 1 await cache.deleteByTag({ tags: ['user:1'] }) ``` -------------------------------- ### Invalidate User and User List Cache on Deletion Source: https://context7.com/adonisjs/cache/llms.txt When deleting a user, invalidate both the specific user's cache entry using its key and the general user list cache using tags. This ensures related data is also cleared. ```typescript // Invalidate user cache and user list await cache.delete({ key: `user:${params.id}` }) await cache.deleteByTag({ tags: ['user-list'] }) return response.noContent() } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.