@rangeljl/shared
Version:
A set of functions that are used in a lot of places
134 lines (133 loc) • 5.18 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const unixTimestampGet_1 = __importDefault(require("./unixTimestampGet"));
/**
* Creates a cached version of an async function that stores results in RAM for improved performance.
* The cached function includes additional methods for cache management.
*
* @template OriginalArgs - The type of arguments the original function accepts
* @template ReturnValue - The type of value the original function returns
* @param config - Configuration object for the cache
* @param config.originalFunction - The async function to be cached
* @param config.hashArgs - Function that converts arguments to a string hash for caching
* @param config.expirationTimeInSeconds - Cache expiration time in seconds (default: Infinity)
* @param config.debugName - Optional name for debug logging
* @returns A cached version of the original function with additional cache management methods
*
* @example
* ```typescript
* const cachedFetch = asyncFunctionAddCache({
* originalFunction: fetchUserData,
* hashArgs: (userId) => `user-${userId}`,
* expirationTimeInSeconds: 300, // 5 minutes
* debugName: 'UserDataCache'
* });
*
* // Use the cached function
* const userData = await cachedFetch('123');
*
* // Clear specific cache entry
* cachedFetch.clearCacheRecord('123');
*
* // Clear all cache
* cachedFetch.cacheClear();
* ```
*/
const asyncFunctionAddCache = ({ hashArgs, originalFunction, expirationTimeInSeconds = Infinity, debugName, }) => {
const cacheMap = new Map();
/**
* The cached version of the original function. Automatically handles caching logic
* and cache expiration.
*
* @param args - Arguments to pass to the original function
* @returns Promise that resolves to the cached or freshly computed result
*/
const functionWithCache = (args) => __awaiter(void 0, void 0, void 0, function* () {
const argsHash = hashArgs(args);
const cachedRecord = cacheMap.get(argsHash);
if (cachedRecord) {
const secondsSinceCache = (0, unixTimestampGet_1.default)() - cachedRecord.timestamp;
if (secondsSinceCache < expirationTimeInSeconds) {
if (debugName) {
console.log(`[${debugName}] Cache hit`);
}
return cachedRecord.value;
}
}
if (debugName) {
console.log(`[${debugName}] Cache miss`);
}
const value = yield originalFunction(args);
cacheMap.set(argsHash, {
value,
timestamp: (0, unixTimestampGet_1.default)(),
});
return value;
});
/**
* Clears a specific cache entry based on the provided arguments.
*
* @param args - The arguments used to identify which cache entry to clear
*
* @example
* ```typescript
* // Clear cache for specific user
* cachedFunction.clearCacheRecord('user123');
* ```
*/
functionWithCache.clearCacheRecord = (args) => {
cacheMap.delete(hashArgs(args));
};
/**
* Removes cache records based on a custom condition function.
* Useful for selective cache cleanup based on custom criteria.
*
* @param conditionFunction - Function that returns true for records that should be REMOVED from cache
*
* @example
* ```typescript
* // Remove cache entries older than 1 hour
* cachedFunction.removeCacheRecordsWhere((record) => {
* const hourInSeconds = 3600;
* return (unixTimestampGet() - record.timestamp) > hourInSeconds;
* });
* ```
*/
functionWithCache.removeCacheRecordsWhere = (conditionFunction) => {
for (const [hash, record] of cacheMap.entries()) {
if (!record) {
continue;
}
if (!conditionFunction(hash, record)) {
continue;
}
cacheMap.delete(hash);
}
};
/**
* Clears all cached entries, completely resetting the cache.
*
* @example
* ```typescript
* // Clear all cached data
* cachedFunction.cacheClear();
* ```
*/
functionWithCache.cacheClear = () => {
cacheMap.clear();
};
return functionWithCache;
};
exports.default = asyncFunctionAddCache;