Skip to main content

Cache Utilities

This section covers the utilities provided for cache drivers.

Parse Cache Key

The parseCacheKey function parses a cache key (string or object), sanitizes it, and returns a dot.notation string. This helps avoid key collisions and makes cache keys predictable.

When to Use

  • When using objects as cache keys (e.g., for query filters)
  • When you want consistent, readable cache keys

Examples

src/app/main.ts
import { parseCacheKey } from "@warlock.js/core";

console.log(parseCacheKey("users:1")); // users.1

const filter = {
limit: 3,
page: 1,
search: "John",
};
console.log(parseCacheKey(filter)); // limit.3.page.1.search.John

const nested = {
user: { id: 5 },
tags: ["a", "b"],
};
console.log(parseCacheKey(nested)); // user.id.5.tags.a.b

With Global Prefix

import { parseCacheKey } from "@warlock.js/core";

const options = { globalPrefix: "myapp" };
console.log(parseCacheKey("user:1", options)); // myapp.user.1

Tip

Use this utility for cache keys in repositories, API responses, or any place where the key might be an object.

Expiration Constants

The EXPIRES_AFTER enum provides common TTL values for easy use:

import { EXPIRES_AFTER } from "@warlock.js/core";

// Common expiration times
await cache.set("temp", data, EXPIRES_AFTER.HALF_HOUR); // 30 minutes
await cache.set("session", data, EXPIRES_AFTER.ONE_HOUR); // 1 hour
await cache.set("daily", data, EXPIRES_AFTER.ONE_DAY); // 24 hours
await cache.set("weekly", data, EXPIRES_AFTER.ONE_WEEK); // 7 days
await cache.set("monthly", data, EXPIRES_AFTER.ONE_MONTH); // 30 days

Available Constants

ConstantValue (seconds)Description
HALF_HOUR180030 minutes
ONE_HOUR36001 hour
HALF_DAY4320012 hours
ONE_DAY8640024 hours
ONE_WEEK6048007 days
HALF_MONTH129600015 days
ONE_MONTH259200030 days
TWO_MONTHS518400060 days
SIX_MONTHS15768000180 days
ONE_YEAR31536000365 days

Real-World Example

import { cache } from "@warlock.js/core";
import { EXPIRES_AFTER } from "@warlock.js/core";

class UserService {
async getUser(id: number) {
const cacheKey = `user:${id}`;

// Try to get from cache first
let user = await cache.get(cacheKey);

if (!user) {
// Fetch from database
user = await this.fetchFromDatabase(id);

// Cache for 1 hour
await cache.set(cacheKey, user, EXPIRES_AFTER.ONE_HOUR);
}

return user;
}

async getUserList(filters: any) {
const cacheKey = filters; // Object will be parsed automatically

let users = await cache.get(cacheKey);

if (!users) {
users = await this.fetchUsersFromDatabase(filters);

// Cache for 30 minutes
await cache.set(cacheKey, users, EXPIRES_AFTER.HALF_HOUR);
}

return users;
}
}