@divine-lab/cache
v1.1.1
Published
A simple utility library for easy interactions with redis as a cache.
Readme
@divine-lab/cache
readme version: 0.1.2
Simple and opinionated caching utility.
This package aims to make using redis cache easy and simple for small scale applications by providing utility functions to interact with redis as a cache.
Setup
This library depends on 2 environment variables for configuration:
| Env Variables | Description | | ------------------------------- | --------------------------------------------------------------------------------------------------------- | | DIVINE_LAB_CACHE_REDIS_URL | (Required) This environment variable set’s the url of the redis instance which will be used as a cache. | | DIVINE_LAB_CACHE_REDIS_PASSWORD | (optional) This environment variable set’s the password to be used when connecting to the redis instance. |
Usage
The library provides an object called cache which provides 4 main functions to get, set and invalidate cache data.
set
This function is quite simple in it’s use. It is used to store data in the cache.
Arguments (in order):
- key [String]: This is the key which will store the cache data.
- value [any]: This is the data which will be stored.
- expireInSecs [number]: This defines the time after which a cache should be invalidated automatically. Entering 0 will make the cache indefinite. (Explicit over implicit)
import cache from "@divine-lab/cache";
await cache.set("user:1", { id: 1, name: "user 1" }, 100);get
This function is used to retrieve data from the cache. It will return null if the data does not exist.
Template:
- T: The type of the returned data
Arguments (in order):
- key [String]: The key to be used to retrieve data.
import cache from "@divine-lab/cache";
const data = await cache.get<UserType>("user:1");
if (data === null) throw new Error("User not found");
else console.log("User found: ", data);invalidate
This function is simple in it’s use to invalidate a number of keys from the cache.
Arguments (in order):
- keys [Array<string>]: The keys to be invalidated
import cache from "@divine-lab/cache";
const keys = ["user:1", "users"];
await cache.invalidate(keys);invalidatePrefixes
An advanced version of the invalidate function, It invalidates any keys with the provided prefixes.
Arguments (in order):
- prefixes [Array<string>]: Array of key prefixes to invalidate.
import cache from "@divine-lab/cache";
// Invalidate all cache for users.
await cache.invalidatePrefixes(["user"]);Updates
- 1.0.0: updated dependency version @divine-lab/logger to v2.0.1
- 1.0.1: Fixed function name for invalidatePrefixes
- 1.0.2: Moved Cache URL and password initialization code into index.ts and now uses Symbol for cross dependency consistency.
- 1.1.0: Added new method setNx for atomic set operation.
- 1.1.1: Added ENV variable to disable initialization logs, updated dependency version of @divine-lab/logger to 3.0.3
