Caching
Powerful caching utilities to reduce database and API requests.
In order to reduce the number of database or external API requests, this framework provides two built-in caching utilities: a simple Cache
class for temporary values and an advanced ResponseCache
class for asynchronous queries. Both are located in src/app/util.ts
and is imported by default in the app
namespace.
Simple Cache
The Cache
class allows you to temporarily store and retrieve values using a key. It's useful for short-term storage and can ensure that default values are set if a key doesn't exist.
Example Usage
Methods
get(key: string)
: Retrieves the cached value for the given key. Returnsundefined
if the key doesn't exist.set(key: string, value: any)
: Stores a value with the given key.delete(key: string)
: Removes the value associated with the given key.ensure(key: string, defaultValue: T)
: Retrieves the value for the key or sets it todefaultValue
if the key is not found.
Good practices
ResponseCache from @ghom/orm
@ghom/orm
The ResponseCache
class is designed for caching results of asynchronous queries. It can store the response of a function for a specified timeout period, ensuring that repeated requests within this period return the cached result rather than triggering a new query.
Examples Usage
1. Create a new ResponseCache for a slow API request.
If you have a slow API request that you want to cache for a specific time, you can create a new ResponseCache.
2. Use the built-in ResponseCache for a slow SQL query.
Example in a src/namespaces/players.ts
namespace with a src/tables/players.ts
table.
Methods
get(id: string, ...params: Params)
: Retrieves the cached value for the provided parameters if it exists and hasn't expired. Otherwise, it performs the request and stores the result.fetch(id: string, ...params: Params)
: Always performs the request and updates the cached value, regardless of whether the value is already cached.invalidate(id: string)
: Removes the cached value for the provided identifier.
Use Cases
Simple Cache: Ideal for quick lookups or storing frequently accessed data temporarily, such as configuration values or session-specific information.
ResponseCache: Best suited for reducing API calls or database queries where the response does not change often and can be reused within a specific time window.
Last updated
Was this helpful?