revalidateTag Function
The revalidateTag
function allows you to invalidate cache entries that are tagged with a specific tag. This is useful for refreshing data when it changes or when you need to force a cache update.
Basic Usage
import { revalidateTag } from '@commandkit/cache';
// Invalidate all cache entries tagged with 'user:123'
await revalidateTag('user:123');
How It Works
When you call revalidateTag
:
- It finds all cache entries with the specified tag
- Marks them for invalidation
- The next time these entries are accessed, they will be refreshed
Example Use Cases
Updating User Data
async function updateUserProfile(userId: string, data: UserData) {
// Update the database
await db.users.update(userId, data);
// Invalidate all cached user data
await revalidateTag(`user:${userId}`);
}
Bulk Updates
async function updateGuildSettings(guildId: string, settings: GuildSettings) {
// Update multiple settings
await db.guilds.update(guildId, settings);
// Invalidate all related cache entries
await revalidateTag(`guild:${guildId}`);
await revalidateTag('guild:settings');
}
Scheduled Revalidation
// Revalidate weather data every hour
setInterval(
async () => {
await revalidateTag('weather');
},
60 * 60 * 1000,
);
Best Practices
-
Strategic Invalidation:
- Invalidate only what needs to be refreshed
- Use specific tags for targeted invalidation
- Consider the impact on performance
-
Timing:
- Invalidate after data changes
- Consider using scheduled revalidation
- Balance freshness and performance
-
Tag Organization:
- Use consistent tag naming
- Group related tags
- Make tags meaningful
Common Patterns
Resource Updates
// User updates
await revalidateTag(`user:${userId}`);
await revalidateTag(`user:${userId}:profile`);
await revalidateTag(`user:${userId}:settings`);
// Guild updates
await revalidateTag(`guild:${guildId}`);
await revalidateTag(`guild:${guildId}:members`);
await revalidateTag(`guild:${guildId}:roles`);
Category Updates
// Content updates
await revalidateTag('content:announcements');
await revalidateTag('content:rules');
await revalidateTag('content:welcome');
// System updates
await revalidateTag('system:config');
await revalidateTag('system:stats');
await revalidateTag('system:logs');