Skip to content

Instantly share code, notes, and snippets.

@bazuka5801
Created September 8, 2024 23:00
Show Gist options
  • Save bazuka5801/1aaf0676cc306a653409c7867680bcd7 to your computer and use it in GitHub Desktop.
Save bazuka5801/1aaf0676cc306a653409c7867680bcd7 to your computer and use it in GitHub Desktop.
// Usage
/*
Here, the redisificationResult function is being used to cache the result of the getPaidSeatsOfServices
function call for a specific eventId.
The cacheSeconds is set to 60, which means the result will be cached in Redis for 1 minute.
The key is dynamically generated based on the eventId, which allows for caching different results for different events.
By using redisificationResult, the code is ensuring that if the same eventId is passed again within the 1-minute cache window,
the result will be retrieved from the cache instead of re-executing the getPaidSeatsOfServices function.
This can help improve performance by reducing the number of redundant function calls.
*/
const paidSeatsTable = await redisificationResult({
cacheSeconds: 60,
key: `getPaidSeatsOfServices_${input.eventId}`
},
() => getPaidSeatsOfServices(input.eventId));
// Redis client
import client from '../../utils/connectRedis';
/**
* A helper function to cache the result of an async function in Redis.
*
* @param options - an object with a `cacheSeconds` property and a `key` property
* @param fn - the async function to be cached
* @returns the cached result if it exists, or the result of the function
*
* How it works:
* 1. It first tries to find a cached result in Redis by the `key` provided.
* 2. If the result is found, it parses the cached result back into a JSON object and returns it.
* 3. If the result is not found, it calls the `fn` function and caches its result
* in Redis with the provided `key` and `cacheSeconds` TTL.
* 4. Finally, it returns the cached result.
*/
export async function redisificationResult<FnResult>(
options: { cacheSeconds: number, key: string },
fn: () => Promise<FnResult> ): Promise<FnResult> {
const cachedResult = await client.get(options.key);
if (cachedResult !== null) {
// If the result is found in Redis, parse it back into a JSON object and return it.
return JSON.parse(cachedResult);
}
// If the result is not found, call the function and cache its result.
const result = await fn();
// Cache the result in Redis with the provided key and TTL.
await client.set(options.key, JSON.stringify(result), {
EX: options.cacheSeconds // in Seconds
});
// Return the cached result.
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment