Create Redis Key - Easy Way to Configure All Your Redis Keys In One Place
Tags: redis, node, typescript, npm
Published: 2022-08-26 20:55:00

Create Redis Key is an NPM package, a Redis key creation utility for NodeJS (most effective when used with Typescript).

## Sections

- [Motivation](#motivation)
- [The Package](#create-redis-key)
- [How To Use](#usage)

## Motivation

You might be wondering "Why would I need a package to create a Redis key? Isn't it just a string?"

Well, it is.

But even if an individual key is a string, most of the time we use many of them. Cache this, cache that, Cache 'Em All!

Have you ever had a backend app which utilizes Redis a primary database? 

I have one. A microservice which has many resources stored in Redis. It stores data that change in an expected time span, varying from less than a second to hours.

There comes the critical part(s): whether it be caching or storing data, keys mostly **share a template** & what makes individual keys different is that these keys **include resource identifiers** as a part of them since they are trying to locate different resources. Also, if a resource belongs to another resource, it's **key starts with the key of the resource it belongs to**.

Let's take Instagram as an example.

Simply we can store a user with id 1 at the key `users:1`. Then it makes sense to store the user with id 2 at the key `users:2` and it goes on.

As we can see they share the template `users:%UserID%` and the template includes a resource identifier.

There are different kind of resources which belongs to a user like follows, followers, posts etc. We can store them at keys `users:%UserID%:follows`, `users:%UserID%:followers`, `users:%UserID%:posts` which start with the key of the resource they belong to (`users:%UserID%`).

So, wouldn't it be nice if we had a way to easily manage all our keys?

Introducing Create Redis Key.

## Create Redis Key

A Redis key creation utility.

Create `Redis Key Templates`, which include parameters, using a nested config object & use your `Redis Key Template` strings to create Redis Keys.



See [create-redis-key](https://www.npmjs.com/package/create-redis-key) on NPM.

See [create-redis-key](https://github.com/alper-guven/create-redis-key) on GitHub.


## Usage

First of all, import needed functions as follows: 

```typescript
import {
  createRedisKeyParam,
  createRedisKeysMap,
  createRedisKey,
} from 'create-redis-key';
```

Create a `Redis Keys Config` object.

> You should write `as const` at the end of the object for Typescript types to properly work.

```typescript
const redisKeysConfig = {
  SCOPE_FIRST_PART: [],

  // app-statuses
  appStatus: ['app-statuses'],

  users: {
    SCOPE_FIRST_PART: ['users'],

    // users:online
    online: ['online'],

    byID: {
      SCOPE_FIRST_PART: ['by-id', createRedisKeyParam('UserID')],

      feed: {
        SCOPE_FIRST_PART: ['feed'],

        // users:by-id:%UserID%:feed:following
        following: ['following'],
        // users:by-id:%UserID%:feed:favorites
        favorites: ['favorites'],
      },

      // users:by-id:%UserID%:follows
      follows: ['follows'],
      // users:by-id:%UserID%:followers
      followers: ['followers'],
      posts: {
        SCOPE_FIRST_PART: ['posts'],

        byID: {
          SCOPE_FIRST_PART: ['by-id', createRedisKeyParam('PostID')],

          // users:by-id:%UserID%:posts:by-id:%PostID%:comments
          comments: ['comments'],
          // users:by-id:%UserID%:posts:by-id:%PostID%:likes
          likes: ['likes'],
        },
      },
    },
  },
} as const;
```

Then create a `Redis Keys Templates Map` using the config:

> If you give an invalid config, return type will be `never`.

```typescript
const RedisKeysMap = createRedisKeysMap(redisKeysConfig);
```

The resulting object will be this, which is a `Redis Keys Templates Map`:

```json
{
    "appStatus": "app-statuses",
    "users": {
        "online": "users:online",
        "byID": {
            "feed": {
                "following": "users:by-id:%UserID%:feed:following",
                "favorites": "users:by-id:%UserID%:feed:favorites"
            },
            "follows": "users:by-id:%UserID%:follows",
            "followers": "users:by-id:%UserID%:followers",
            "posts": {
                "byID": {
                    "comments": "users:by-id:%UserID%:posts:by-id:%PostID%:comments",
                    "likes": "users:by-id:%UserID%:posts:by-id:%PostID%:likes"
                }
            }
        }
    }
}
```

You can then use this map to create a Redis key when needed:

> You will get parameter suggestions on your IDE based on the `Redis Key Template` you provided to `createRedisKey()` function. 


> All params on a `Redis Key Template` are required. You will get type errors if you don't provide all of them.


```typescript
const likesOfPostRK = createRedisKey(RedisKeysMap.users.byID.posts.byID.likes, {
  UserID: '1234',
  PostID: '9876',
});
```
You can see the generated key by logging it to console:

```javascript
console.log(likesOfPostRK);
```

The log will be:
```bash
users:by-id:1234:posts:by-id:9876:likes
```

And that's it. You can now use the generated key to read the resource from Redis.

There is actually 3 ways you can use this library. If you liked the idea, you can check more options and documentation on [create-redis-key](https://github.com/alper-guven/create-redis-key) on GitHub.

I want to see your comments. Is this a useful way to do this? Is there any other widely adopted strategy that you have seen on projects you worked on previously? Do you find it easy to use? Would you like to implement it on your existing projects or use it on your future projects?

Happy coding!