@desmat/redis-store
v1.4.0
Published
[](https://www.npmjs.com/package/@desmat/redis-store) [](
Readme
@desmat/redis-store
A lightweight library to facilitate using the (in)famously fast in-memory database as your primary data store for your app’s entities and their relationships.
Leans into Redis’ strong suits to bring relational aspects to the simple but performant KV store:
- Lots of small read/writes
- JSON keys for storing entities (no migration scripts required)
- ZSET keys to track lists and relations
Plays well with Upstash and Vercel but will work with any Redis instance via REST API.
Also ships with MemoryStore, a pure in-memory implementation of RedisStore — a drop-in swap for local development and tests that don't need (or want) a live Redis instance. See In-memory store below.
Installation
Install via npm:
npm install @desmat/redis-storeOr with Yarn:
yarn add @yourusername/redis-storeGetting Started
Below shows a simple schema with users and things belonging to users, some data added then queried.
npm run example to run example.ts.
Setup environment variables
# your .env file, or provided in launch command
KV_REST_API_URL=*****
KV_REST_API_TOKEN=*****Note: Using Vercel KV environment variables enables this library to be used without friction on Vercel's platform, but url and token values can be provided in code.
Setup entities and store
import RedisStore from '@desmat/redis-store';
type User = {
id: string, // required; set by .create as short UUID by default, or can be provided
createdAt: number, // required; set by .create
name: string,
};
type Thing = {
id: string,
createdAt: number,
createdBy: string, // required to lookup Things by Users
label: string,
};
const ThingOptions = {
lookups: {
user: "createdBy", // enables .find({ user: <USERID> })
},
};
// with environment variables `KV_REST_API_URL` and `KV_REST_API_TOKEN`
// otherwise `url` and `token` can be provided to `RedisStore` constructor
const store = {
users: new RedisStore<User>({ key: "user" }),
things: new RedisStore<Thing>({ key: "thing", options: ThingOptions }),
};Create users and things
const users = await Promise.all([
store.users.create({ name: "User One" }),
store.users.create({ name: "User Two" }),
]);
// users (2): [
// { id: '<UUID>', createdAt: <TIMEINMILLIS>, name: 'User One' },
// ...
// ]
// Redis commands executed:
//
// JSON.SET user:<UUID> $ '{ "id": "<UUID>", "createdAt": <TIMEINMILLIS>, "name": "User One" }'
// ZADD users <TIMEINMILLIS> <UUID>
// ...
const things = await Promise.all([
store.things.create({
createdBy: users[0].id,
label: "A thing for user one",
}),
store.things.create({
createdBy: users[0].id,
label: "Another thing for user one",
}),
store.things.create({
createdBy: users[0].id,
label: "Yet another thing for user one",
}),
store.things.create({
createdBy: users[1].id,
label: "A thing for user two",
}),
]);
// things (4): [
// {
// id: '<UUID>',
// createdAt: <TIMEINMILLIS>,
// createdBy: '<USER_UUID>',
// label: 'A thing for user one'
// },
// ...
// ]
// Redis commands executed:
//
// JSON.SET thing:<UUID> $ '{ "id": "<UUID>", "createdAt": <TIMEINMILLIS>, "createdBy": "<USER_UUID>", "message": "Another thing for user one" }'
// ZADD things <TIMEINMILLIS> <UUID>
// ZADD things:user:<USER_UUID> <TIMEINMILLIS> <UUID>
// ...Query things
const allThings = await store.things.find(); // 4 entries
// Redis commands executed:
//
// ZRANGE things:user:<USER_UUID> 0 -1 REV
// JSON.MGET thing:<THING1_UUID> thing:<THING2_UUID> ...
const latestUserThings = await store.things.find({
user: users[0].id
}); // 3 entries
// Redis commands executed:
//
// ZRANGE things:user:<UUID> 0 -1 REV
// JSON.MGET thing:<THING1_UUID> thing:<THING2_UUID> thing:<THING3_UUID>Cleanup (soft delete by default)
await Promise.all([
...users.map((user: User) => store.users.delete(user.id)),
...things.map((thing: Thing) => store.things.delete(thing.id)),
]);
// Redis commands executed:
//
// JSON.SET user:<UUID> $.deletedAt <TIMEINMILLIS>
// ZREM users <UUID>
// ...
// JSON.SET thing:<UUID> $.deletedAt <TIMEINMILLIS>
// ZREM things <UUID>
// ZREM testthings:user:<USER_UUID> <UUID>
// ...In-memory store
MemoryStore<T> implements the exact same Store<T> interface as RedisStore<T> but keeps everything in plain JS Maps — no Redis connection, no environment variables, no network calls. Application code written against Store<T> can swap between the two without any changes.
import { MemoryStore } from '@desmat/redis-store';
const store = {
users: new MemoryStore<User>({ key: "user" }),
things: new MemoryStore<Thing>({ key: "thing", options: ThingOptions }),
};
const user = await store.users.create({ name: "User One" });
const things = await store.things.find({ user: user.id });Useful for:
- Local development without provisioning a real Redis instance
- Test suites that need fast, isolated, disposable data (each
MemoryStoreinstance is its own private state — nothing persists between processes, and nothing is shared unless you share the instance)
Constructor accepts an optional seed array to pre-populate records (and their lookup indices) at construction time, so seeded data is immediately queryable via find/ids without needing to call .create() for each one:
const things = new MemoryStore<Thing>({
key: "thing",
options: ThingOptions,
seed: [
{ id: "thing-1", createdAt: Date.now(), createdBy: "user-1", label: "Seeded thing" },
],
});Notes on parity with RedisStore:
create/update/delete/lookup/counter semantics are ported 1:1, including Redis's rank-based (not score-range) windowing forcount/offsetinids()/find(), andqueryCounter's lexicographic range-bound behavior forincCounters/queryCounter.options.expireis a no-op (data is ephemeral for the life of the process anyway).- There's no equivalent to
RedisStore's raw.redisclient escape hatch — code that reaches through it directly for one-off scripts (rather than going through theStore<T>methods) isn't portable toMemoryStore.
Testing
npm testRuns the MemoryStore unit test suite (test/*.test.ts) via Node's built-in test runner (through tsx) — no live Redis needed. RedisStore itself has no automated tests; it's a thin wrapper around @upstash/redis.
