@stead/redis-json
TypeScript icon, indicating that this package has built-in type declarations

0.0.1 • Public • Published

Redis Json

A node library that maintains type persistence of objects stored in redis

Installation

yarn add redis-json

API

Please visit this page for detailed API documentation.

Usage

Simple

import Redis from 'ioredis';
import { RedisJson } from '@stead/redis-json';

const redis = new Redis() as any;

const reJson = new RedisJson<{
  name: string;
  age: 25;
  address: {
    doorNo: string;
    locality: string;
    pincode: number;
  }
}>(redis, {prefix: 'cache:'});

const user = {
  name: 'redis-json',
  age: 25,
  address: {
    doorNo: '12B',
    locality: 'pentagon',
    pincode: 123456
  },
  cars: ['BMW 520i', 'Audo A8']
}

await reJson.set('123', user)

await reJson.get('123')
// output
// {
//   name: 'redis-json',
//   age: 25,
//   address: {
//     doorNo: '12B',
//     locality: 'pentagon',
//     pincode: 123456
//   },
//   cars: ['BMW 520i', 'Audo A8']
// }

await reJson.set('123', {gender: 'male'})
await reJson.get('123')
// output
// {
//   name: 'redis-json',
//   age: 25,
//   address: {
//     doorNo: '12B',
//     locality: 'pentagon',
//     pincode: 123456
//   },
//   cars: ['BMW 520i', 'Audo A8']
//   gender: 'male'
// }

await reJson.get('123', 'name', 'age');
// output
// {
//   name: 'redis-json',
//   age: 25,
// }

await reJson.get('123', 'name', 'address.doorNo');
// {
//   name: 'redis-json',
//   address: {
//     doorNo: '12B'
//   }
// }

await reJson.clearAll();

await reJson.get('123');
// undefined

With custom stringifier and parser:

const reJson = new RedisJson(redis, {
  stringifier: {
    Date: (val: Date) => val.toISOString()
  },
  parser: {
    Date: (str: string) => new Date(str)
  }
})

const date = new Date()
await reJson.set('test', {
  date: date
})

const result = await reJson.get('test')
result.date == date /// true
// Redis hashset
> hgetall rj:test /// data
1) "date"
2) "2020-05-17T14:41:45.861Z"
> hgetall rj:test_t /// type info
1) "date"
2) "Date"

With transactions:

const transaction = redisClient.multi();

transaction
  .set('name', 'foo')
  .set('bar', 'baz')

reJson.setT(transaction, 'test', {name: 'testing'})
reJson.delT(transaction, 'test1')
reJson.rewriteT(transaction, 'test2', {name: 'testing', age: 25})

transaction.exec((err, replies) => {
/// your logic here after
})

Please note that only setT(), rewriteT() & delT() supports transaction, where as get() & clearAll() do NOT support transaction because we process those results before returning it to the calling function. Moreover there is no real usecase in adding get methods to a transaction!

Readme

Keywords

none

Package Sidebar

Install

npm i @stead/redis-json

Weekly Downloads

1

Version

0.0.1

License

MIT

Unpacked Size

65.2 kB

Total Files

23

Last publish

Collaborators

  • mecolela