@desmat/redis-store 1.0.2 → 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,13 +1,31 @@
1
1
  # @desmat/redis-store
2
2
 
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
+
3
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.
4
7
 
5
- Leans into Redis’ strong suits to bring relational aspects to a simple but performant KV store:
8
+ Leans into Redis’ strong suits to bring relational aspects to the simple but performant KV store:
6
9
  - Lots of small read/writes
7
10
  - JSON keys for storing entities (no migration scripts required)
8
11
  - ZSET keys to track lists and relations
9
12
 
10
- Plays well with Upstash and Vercel but any Redis instance supported via REST API.
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
22
+ ```
23
+
24
+ Or with Yarn:
25
+
26
+ ```bash
27
+ yarn add @yourusername/redis-store
28
+ ```
11
29
 
12
30
 
13
31
  ## Getting Started
@@ -16,11 +34,6 @@ Below shows a simple schema with users and things belonging to users, some data
16
34
 
17
35
  `npm run example` to run [example.ts](./src/example.ts).
18
36
 
19
- ### Install the library into your project
20
-
21
- ```bash
22
- npm install @desmat/redis-store
23
- ```
24
37
 
25
38
  ### Setup environment variables
26
39
 
package/dist/example.js CHANGED
@@ -14,76 +14,15 @@ const ThingOptions = {
14
14
  // or `url` and `token` keys provided to RedisStore constructor
15
15
  const store = {
16
16
  users: new index_1.default({ key: "user" }),
17
- things: new index_1.default({ key: "thing", options: ThingOptions }),
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 }),
18
20
  };
19
21
  (async function () {
20
- // create users
21
- const users = await Promise.all([
22
- store.users.create({ name: "User One" }),
23
- store.users.create({ name: "User Two" }),
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 }),
24
26
  ]);
25
- // Redis commands executed:
26
- // JSON.SET user:<UUID> $ '{ "id": "<UUID>", "createdAt": <TIMEINMILLIS>, "name": "User One" }'
27
- // ZADD users <TIMEINMILLIS> <UUID>
28
- // ...
29
- console.log("users", users);
30
- // users (2 entries): [
31
- // { id: '<UUID>', createdAt: <TIMEINMILLIS>, name: 'User One' },
32
- // ...
33
- // ]
34
- // create things
35
- const things = await Promise.all([
36
- store.things.create({
37
- createdBy: users[0].id,
38
- label: "A thing for user one",
39
- }),
40
- store.things.create({
41
- createdBy: users[0].id,
42
- label: "Another thing for user one",
43
- }),
44
- store.things.create({
45
- createdBy: users[0].id,
46
- label: "Yet another thing for user one",
47
- }),
48
- store.things.create({
49
- createdBy: users[1].id,
50
- label: "A thing for user two",
51
- }),
52
- ]);
53
- // JSON.SET thing:<UUID> $ '{ "id": "<UUID>", "createdAt": <TIMEINMILLIS>, "createdBy": "<USER_UUID>", "message": "Another thing for user one" }'
54
- // ZADD things <TIMEINMILLIS> <UUID>
55
- // ZADD things:user:<USER_UUID> <TIMEINMILLIS> <UUID>
56
- // ...
57
- console.log("things", things);
58
- // things (4 entries): [
59
- // {
60
- // id: '<UUID>',
61
- // createdAt: <TIMEINMILLIS>,
62
- // createdBy: '<USER_UUID>',
63
- // label: 'A thing for user one'
64
- // },
65
- // ...
66
- // ]
67
- // all things
68
- const allThings = await store.things.find();
69
- // ZRANGE things:user:<USER_UUID> 0 -1 REV
70
- // JSON.MGET thing:<THING1_UUID> thing:<THING2_UUID> ...
71
- console.log("allThings", allThings); // 4 entries
72
- // latest things from first user
73
- const latestUserThings = await store.things.find({ user: users[0].id });
74
- // ZRANGE things:user:<USER_UUID> 0 -1 REV
75
- // JSON.MGET thing:<THING1_UUID> thing:<THING2_UUID> thing:<THING3_UUID>
76
- console.log("latestUserThings", latestUserThings); // 3 entries
77
- // cleanup from this session (soft delete by default)
78
- await Promise.all([
79
- ...users.map((user) => store.users.delete(user.id)),
80
- ...things.map((thing) => store.things.delete(thing.id)),
81
- ]);
82
- // JSON.SET user:<UUID> $.deletedAt <TIMEINMILLIS>
83
- // ZREM users <UUID>
84
- // ...
85
- // JSON.SET thing:<UUID> $.deletedAt <TIMEINMILLIS>
86
- // ZREM things <UUID>
87
- // ZREM testthings:user:<USER_UUID> <UUID>
88
- // ...
27
+ console.log("counts", { users: users.size, haikuUsers: haikuUsers.size, userHaikus: userHaikus.size });
89
28
  })();
package/dist/index.js CHANGED
@@ -24,9 +24,15 @@ const utils_1 = require("@desmat/utils");
24
24
  const redis_1 = require("@upstash/redis");
25
25
  class RedisStore {
26
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`';
27
33
  this.redis = new redis_1.Redis({
28
- url: url || process.env.KV_REST_API_URL,
29
- token: token || process.env.KV_REST_API_TOKEN
34
+ url: _url,
35
+ token: _token
30
36
  });
31
37
  this.key = key;
32
38
  this.setKey = setKey || key + "s";
@@ -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.2",
3
+ "version": "1.0.4",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "exports": {
@@ -19,6 +19,7 @@
19
19
  "type": "git",
20
20
  "url": "https://github.com/desmat/redis-store.git"
21
21
  },
22
+ "homepage": "https://www.npmjs.com/package/@desmat/redis-store",
22
23
  "keywords": [
23
24
  "utility",
24
25
  "library",