@desmat/redis-store 1.0.1 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,30 +1,173 @@
1
- # redis-store
2
- A lightweight wrapper for using Redis as a data store
1
+ # @desmat/redis-store
3
2
 
4
- ## To build
3
+ [![NPM Version](https://img.shields.io/npm/v/%40desmat%2Fredis-store?link=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2F%40desmat%2Futils)](https://www.npmjs.com/package/@desmat/redis-store)
4
+ [![license](https://img.shields.io/npm/l/@desmat/utils?link=LICENSE)](LICENSE)
5
+
6
+ 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.
7
+
8
+ Leans into Redis’ strong suits to bring relational aspects to the simple but performant KV store:
9
+ - Lots of small read/writes
10
+ - JSON keys for storing entities (no migration scripts required)
11
+ - ZSET keys to track lists and relations
12
+
13
+ Plays well with Upstash and Vercel but will work with any Redis instance via REST API.
14
+
15
+
16
+ ## Installation
17
+
18
+ Install via npm:
19
+
20
+ ```bash
21
+ npm install @desmat/redis-store
5
22
  ```
6
- npm run build
23
+
24
+ Or with Yarn:
25
+
26
+ ```bash
27
+ yarn add @yourusername/redis-store
7
28
  ```
8
29
 
9
- ## Example
10
- File `./src/example.ts` demonstrates simple use of this library.
11
30
 
12
- ### To run:
31
+ ## Getting Started
13
32
 
14
- Create `.env` file with:
15
- ```
33
+ Below shows a simple schema with users and things belonging to users, some data added then queried.
34
+
35
+ `npm run example` to run [example.ts](./src/example.ts).
36
+
37
+
38
+ ### Setup environment variables
39
+
40
+ ```bash
41
+ # your .env file, or provided in launch command
16
42
  KV_REST_API_URL=*****
17
- KV_REST_API_TOKEN=****
43
+ KV_REST_API_TOKEN=*****
18
44
  ```
19
- *Note: Using Vercel KV environment variables enables this library to be used without friction on Vercel's platform, but can be overwritten programmatically.*
20
45
 
21
- then:
46
+ *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.*
47
+
48
+ ### Setup entities and store
49
+
50
+ ```typescript
51
+ import RedisStore from '@desmat/redis-store';
52
+
53
+ type User = {
54
+ id: string, // required; set by .create as short UUID by default, or can be provided
55
+ createdAt: number, // required; set by .create
56
+ name: string,
57
+ };
58
+
59
+ type Thing = {
60
+ id: string,
61
+ createdAt: number,
62
+ createdBy: string, // required to lookup Things by Users
63
+ label: string,
64
+ };
65
+
66
+ const ThingOptions = {
67
+ lookups: {
68
+ user: "createdBy", // enables .find({ user: <USERID> })
69
+ },
70
+ };
71
+
72
+ // with environment variables `KV_REST_API_URL` and `KV_REST_API_TOKEN`
73
+ // otherwise `url` and `token` can be provided to `RedisStore` constructor
74
+ const store = {
75
+ users: new RedisStore<User>({ key: "user" }),
76
+ things: new RedisStore<Thing>({ key: "thing", options: ThingOptions }),
77
+ };
22
78
  ```
23
- npm run example
79
+
80
+ ### Create users and things
81
+
82
+ ```typescript
83
+ const users = await Promise.all([
84
+ store.users.create({ name: "User One" }),
85
+ store.users.create({ name: "User Two" }),
86
+ ]);
87
+
88
+ // users (2): [
89
+ // { id: '<UUID>', createdAt: <TIMEINMILLIS>, name: 'User One' },
90
+ // ...
91
+ // ]
92
+
93
+ // Redis commands executed:
94
+ //
95
+ // JSON.SET user:<UUID> $ '{ "id": "<UUID>", "createdAt": <TIMEINMILLIS>, "name": "User One" }'
96
+ // ZADD users <TIMEINMILLIS> <UUID>
97
+ // ...
98
+
99
+ const things = await Promise.all([
100
+ store.things.create({
101
+ createdBy: users[0].id,
102
+ label: "A thing for user one",
103
+ }),
104
+ store.things.create({
105
+ createdBy: users[0].id,
106
+ label: "Another thing for user one",
107
+ }),
108
+ store.things.create({
109
+ createdBy: users[0].id,
110
+ label: "Yet another thing for user one",
111
+ }),
112
+ store.things.create({
113
+ createdBy: users[1].id,
114
+ label: "A thing for user two",
115
+ }),
116
+ ]);
117
+
118
+ // things (4): [
119
+ // {
120
+ // id: '<UUID>',
121
+ // createdAt: <TIMEINMILLIS>,
122
+ // createdBy: '<USER_UUID>',
123
+ // label: 'A thing for user one'
124
+ // },
125
+ // ...
126
+ // ]
127
+
128
+ // Redis commands executed:
129
+ //
130
+ // JSON.SET thing:<UUID> $ '{ "id": "<UUID>", "createdAt": <TIMEINMILLIS>, "createdBy": "<USER_UUID>", "message": "Another thing for user one" }'
131
+ // ZADD things <TIMEINMILLIS> <UUID>
132
+ // ZADD things:user:<USER_UUID> <TIMEINMILLIS> <UUID>
133
+ // ...
24
134
  ```
25
135
 
26
- ### Or alternatively:
136
+ ### Query things
137
+
138
+ ```typescript
139
+ const allThings = await store.things.find(); // 4 entries
140
+
141
+ // Redis commands executed:
142
+ //
143
+ // ZRANGE things:user:<USER_UUID> 0 -1 REV
144
+ // JSON.MGET thing:<THING1_UUID> thing:<THING2_UUID> ...
27
145
 
146
+ const latestUserThings = await store.things.find({
147
+ user: users[0].id
148
+ }); // 3 entries
149
+
150
+ // Redis commands executed:
151
+ //
152
+ // ZRANGE things:user:<UUID> 0 -1 REV
153
+ // JSON.MGET thing:<THING1_UUID> thing:<THING2_UUID> thing:<THING3_UUID>
28
154
  ```
29
- export KV_REST_API_URL=***** KV_REST_API_TOKEN=***** && npm run example
155
+
156
+ ### Cleanup (soft delete by default)
157
+
158
+ ```typescript
159
+ await Promise.all([
160
+ ...users.map((user: User) => store.users.delete(user.id)),
161
+ ...things.map((thing: Thing) => store.things.delete(thing.id)),
162
+ ]);
163
+
164
+ // Redis commands executed:
165
+ //
166
+ // JSON.SET user:<UUID> $.deletedAt <TIMEINMILLIS>
167
+ // ZREM users <UUID>
168
+ // ...
169
+ // JSON.SET thing:<UUID> $.deletedAt <TIMEINMILLIS>
170
+ // ZREM things <UUID>
171
+ // ZREM testthings:user:<USER_UUID> <UUID>
172
+ // ...
30
173
  ```
package/dist/example.js CHANGED
@@ -1,93 +1,28 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const index_1 = require("./index");
6
+ const index_1 = __importDefault(require("./index"));
4
7
  require('dotenv').config();
5
- const ThingRecordOptions = {
8
+ const ThingOptions = {
6
9
  lookups: {
7
10
  user: "createdBy", // enable .find({ user: <USERID> })
8
11
  },
9
12
  };
13
+ // with environment variables KV_REST_API_URL and KV_REST_API_TOKEN
14
+ // or `url` and `token` keys provided to RedisStore constructor
10
15
  const store = {
11
- users: new index_1.RedisStore({
12
- key: "user",
13
- options: { hardDelete: false },
14
- }),
15
- things: new index_1.RedisStore({
16
- key: "thing",
17
- options: {
18
- ...ThingRecordOptions,
19
- hardDelete: false
20
- }
21
- }),
16
+ users: new index_1.default({ key: "user" }),
17
+ haikuUsers: new index_1.default({ key: "haikuuser" }),
18
+ userHaikus: new index_1.default({ key: "userhaiku" }),
19
+ // things: new RedisStore<Thing>({ key: "thing", options: ThingOptions }),
22
20
  };
23
21
  (async function () {
24
- // create users
25
- const users = await Promise.all([
26
- store.users.create({ name: "User One" }),
27
- store.users.create({ name: "User Two" }),
28
- ]);
29
- // Redis commands executed:
30
- // JSON.SET user:<UUID> $ '{ "id": "<UUID>", "createdAt": <TIMEINMILLIS>, "name": "User One" }'
31
- // ZADD users <TIMEINMILLIS> <UUID>
32
- // ...
33
- console.log("users", users);
34
- // users (2 entries): [
35
- // { id: '<UUID>', createdAt: <TIMEINMILLIS>, name: 'User One' },
36
- // ...
37
- // ]
38
- // create things
39
- const things = await Promise.all([
40
- store.things.create({
41
- createdBy: users[0].id,
42
- label: "A thing for user one",
43
- }),
44
- store.things.create({
45
- createdBy: users[0].id,
46
- label: "Another thing for user one",
47
- }),
48
- store.things.create({
49
- createdBy: users[0].id,
50
- label: "Yet another thing for user one",
51
- }),
52
- store.things.create({
53
- createdBy: users[1].id,
54
- label: "A thing for user two",
55
- }),
56
- ]);
57
- // JSON.SET thing:<UUID> $ '{ "id": "<UUID>", "createdAt": <TIMEINMILLIS>, "createdBy": "<USER_UUID>", "message": "Another thing for user one" }'
58
- // ZADD things <TIMEINMILLIS> <UUID>
59
- // ZADD things:user:<USER_UUID> <TIMEINMILLIS> <UUID>
60
- // ...
61
- console.log("things", things);
62
- // things (4 entries): [
63
- // {
64
- // id: '<UUID>',
65
- // createdAt: <TIMEINMILLIS>,
66
- // createdBy: '<USER_UUID>',
67
- // label: 'A thing for user one'
68
- // },
69
- // ...
70
- // ]
71
- // all things
72
- const allThings = await store.things.find();
73
- // ZRANGE things:user:<USER_UUID> 0 -1 REV
74
- // JSON.MGET thing:<THING1_UUID> thing:<THING2_UUID> ...
75
- console.log("allThings", allThings); // 4 entries
76
- // latest things from first user
77
- const latestUserThings = await store.things.find({ user: users[0].id });
78
- // ZRANGE things:user:<USER_UUID> 0 -1 REV
79
- // JSON.MGET thing:<THING1_UUID> thing:<THING2_UUID> thing:<THING3_UUID>
80
- console.log("latestUserThings", latestUserThings); // 3 entries
81
- // cleanup from this session (soft delete by default)
82
- await Promise.all([
83
- ...users.map((user) => store.users.delete(user.id)),
84
- ...things.map((thing) => store.things.delete(thing.id)),
22
+ const [users, haikuUsers, userHaikus] = await Promise.all([
23
+ store.users.ids({ scan: "*", count: 999999 }),
24
+ store.haikuUsers.ids({ scan: "*", count: 999999 }),
25
+ store.userHaikus.ids({ scan: "*", count: 999999 }),
85
26
  ]);
86
- // JSON.SET user:<UUID> $.deletedAt <TIMEINMILLIS>
87
- // ZREM users <UUID>
88
- // ...
89
- // JSON.SET thing:<UUID> $.deletedAt <TIMEINMILLIS>
90
- // ZREM things <UUID>
91
- // ZREM testthings:user:<USER_UUID> <UUID>
92
- // ...
27
+ console.log("counts", { users: users.size, haikuUsers: haikuUsers.size, userHaikus: userHaikus.size });
93
28
  })();
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export type RedisStoreRecord = {
5
5
  updatedAt?: number;
6
6
  deletedAt?: number;
7
7
  };
8
- export declare class RedisStore<T extends RedisStoreRecord> {
8
+ export default class RedisStore<T extends RedisStoreRecord> {
9
9
  redis: Redis;
10
10
  key: string;
11
11
  setKey: string;
package/dist/index.js CHANGED
@@ -19,15 +19,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
19
19
  return (mod && mod.__esModule) ? mod : { "default": mod };
20
20
  };
21
21
  Object.defineProperty(exports, "__esModule", { value: true });
22
- exports.RedisStore = void 0;
23
22
  const moment_1 = __importDefault(require("moment"));
24
23
  const utils_1 = require("@desmat/utils");
25
24
  const redis_1 = require("@upstash/redis");
26
25
  class RedisStore {
27
26
  constructor({ url, token, key, setKey, options, debug, }) {
27
+ const _url = url || process.env.KV_REST_API_URL;
28
+ const _token = token || process.env.KV_REST_API_TOKEN;
29
+ if (!_url)
30
+ throw 'Error creating RedisStore: `url` is required: either provide in constructor or via environment variable `KV_REST_API_URL`';
31
+ if (!_token)
32
+ throw 'Error creating RedisStore: `token` is required: either provide in constructor or via environment variable `KV_REST_API_TOKEN`';
28
33
  this.redis = new redis_1.Redis({
29
- url: url || process.env.KV_REST_API_URL,
30
- token: token || process.env.KV_REST_API_TOKEN
34
+ url: _url,
35
+ token: _token
31
36
  });
32
37
  this.key = key;
33
38
  this.setKey = setKey || key + "s";
@@ -275,4 +280,4 @@ class RedisStore {
275
280
  return value ? { ...value, deletedAt } : undefined;
276
281
  }
277
282
  }
278
- exports.RedisStore = RedisStore;
283
+ exports.default = RedisStore;
@@ -0,0 +1,38 @@
1
+ declare let RedisStore: any;
2
+ declare let moment: typeof moment;
3
+ declare let debug: boolean;
4
+ type User = {
5
+ id: string;
6
+ createdAt: number;
7
+ name: string;
8
+ } | any;
9
+ type Post = {
10
+ id: string;
11
+ createdAt: number;
12
+ createdBy: string;
13
+ message: string;
14
+ } | any;
15
+ declare let PostOptions: {
16
+ lookups: {
17
+ user: string;
18
+ };
19
+ };
20
+ type UserPost = {
21
+ id: string;
22
+ createdAt: number;
23
+ userId: string;
24
+ postId: string;
25
+ viewedAt: number;
26
+ likedAt: number;
27
+ } | any;
28
+ declare let UserPostOptions: {
29
+ lookups: {
30
+ user: string;
31
+ post: string;
32
+ };
33
+ };
34
+ declare let store: {
35
+ users: any;
36
+ posts: any;
37
+ userPosts: any;
38
+ };
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ let RedisStore = require("./index");
3
+ // @ts-ignore
4
+ let moment = require("moment");
5
+ require('dotenv').config();
6
+ let debug = false;
7
+ let PostOptions = {
8
+ lookups: {
9
+ user: "createdBy",
10
+ },
11
+ };
12
+ let UserPostOptions = {
13
+ lookups: {
14
+ user: "userId",
15
+ post: "postId",
16
+ },
17
+ };
18
+ console.log(RedisStore);
19
+ let store = {
20
+ users: new RedisStore({ key: "testuser", debug }),
21
+ posts: new RedisStore({ key: "testpost", options: PostOptions, debug }),
22
+ userPosts: new RedisStore({ key: "testuserpost", options: UserPostOptions, debug }),
23
+ };
24
+ (async function () {
25
+ // new user signs up
26
+ let users = await Promise.all([
27
+ store.users.create({ name: "User One" }),
28
+ store.users.create({ name: "User Two" }),
29
+ store.users.create({ name: "User Three" }),
30
+ ]);
31
+ console.log("\n=== Users ===");
32
+ users.forEach((user) => {
33
+ console.log(`[user ${user.id}]: ${user.name}`);
34
+ });
35
+ // users creates posts
36
+ let posts = await Promise.all([
37
+ store.posts.create({
38
+ createdBy: users[0].id,
39
+ message: "A post by user one",
40
+ }),
41
+ store.posts.create({
42
+ createdBy: users[0].id,
43
+ message: "Another post by user one",
44
+ }),
45
+ store.posts.create({
46
+ createdBy: users[0].id,
47
+ message: "Yet another post by user one",
48
+ }),
49
+ store.posts.create({
50
+ createdBy: users[1].id,
51
+ message: "A post by user two",
52
+ }),
53
+ ]);
54
+ // show latest posts from first user
55
+ let latestPosts = await store.posts.find({ user: users[0].id, count: 3 });
56
+ console.log("\n=== Latest posts ===");
57
+ latestPosts.forEach((post) => {
58
+ console.log(`[post ${post.id}]: ${post.message}`);
59
+ });
60
+ // users views posts
61
+ let userPosts = await Promise.all([
62
+ // createdAt will record post views
63
+ store.userPosts.create({
64
+ id: `${users[1].id}:${posts[0].id}`,
65
+ userId: users[1].id,
66
+ postId: posts[0].id,
67
+ }),
68
+ store.userPosts.create({
69
+ id: `${users[1].id}:${posts[1].id}`,
70
+ userId: users[1].id,
71
+ postId: posts[1].id,
72
+ }),
73
+ // record that this user liked this post
74
+ store.userPosts.create({
75
+ id: `${users[2].id}:${posts[1].id}`,
76
+ userId: users[2].id,
77
+ postId: posts[1].id,
78
+ likedAt: moment().valueOf(),
79
+ }),
80
+ ]);
81
+ // a user likes a post
82
+ userPosts[2] = await store.userPosts.update({
83
+ ...userPosts[2],
84
+ likedAt: moment().valueOf(),
85
+ });
86
+ // load all of a user's viewed posts
87
+ console.log("\n=== A user's viewed posts ===");
88
+ let userViewedPosts = await store.userPosts.find({ user: users[1].id });
89
+ userViewedPosts.forEach((userPost) => {
90
+ console.log(`[user ${userPost.userId}]: ${userPost.id}`);
91
+ });
92
+ // load a post's count of views and likes
93
+ console.log("\n=== A post's views and likes ===");
94
+ let postViews = await store.userPosts.find({ post: posts[1].id });
95
+ console.log(`[post ${posts[1].id}]: ${postViews.filter((userPost) => userPost.viewedAt).length} view(s) and ${postViews.filter((userPost) => userPost.likedAt).length} like(s)`);
96
+ // cleanup from this session
97
+ await Promise.all([
98
+ ...users.map((user) => store.users.delete(user.id, { hardDelete: true })),
99
+ ...posts.map((post) => store.posts.delete(post.id, { hardDelete: true })),
100
+ ...userPosts.map((userPost) => store.userPosts.delete(userPost.id, { hardDelete: true })),
101
+ ]);
102
+ // cleanup all from previous session
103
+ // let [usersToDelete, postsToDelete, userPostsToDelete] = await Promise.all([
104
+ // store.users.ids({ scan: "*" }),
105
+ // store.posts.ids({ scan: "*" }),
106
+ // store.userPosts.ids({ scan: "*" }),
107
+ // ])
108
+ // console.log("users to delete", { usersToDelete, postsToDelete, userPostsToDelete });
109
+ // await Promise.all([
110
+ // // @ts-ignore
111
+ // ...Array.from(usersToDelete).map((id: string) => store.users.delete(id, { hardDelete: true })),
112
+ // // @ts-ignore
113
+ // ...Array.from(postsToDelete).map((id: string) => store.posts.delete(id, { hardDelete: true })),
114
+ // // @ts-ignore
115
+ // ...Array.from(userPostsToDelete).map((id: string) => store.userPosts.delete(id, { hardDelete: true })),
116
+ // ]);
117
+ console.log(store.users.redis);
118
+ })();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@desmat/redis-store",
3
- "version": "1.0.1",
3
+ "version": "1.0.4",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "exports": {
@@ -13,14 +13,13 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "build": "tsc",
16
- "example": "ts-node --skipProject ./src/example.ts",
17
- "repl": "ts-node --skipProject -i -e 'console.log(\"Exec `.load ./scratchpad.ts` to run load a starter environment; Ctrl-D or Ctrl-C twice to exit.\")'",
18
- "scratchpad": "ts-node --skipProject ./scratchpad.ts"
16
+ "example": "ts-node --skipProject ./src/example.ts"
19
17
  },
20
18
  "repository": {
21
19
  "type": "git",
22
20
  "url": "https://github.com/desmat/redis-store.git"
23
21
  },
22
+ "homepage": "https://www.npmjs.com/package/@desmat/redis-store",
24
23
  "keywords": [
25
24
  "utility",
26
25
  "library",