redis nodejs code example

Example 1: redis nodejs

/* npm install redis */

const redis = require("redis");
const client = redis.createClient();

client.on("error", function(error) {
  console.error(error);
});

client.set("key", "value", redis.print);
client.get("key", redis.print);

Example 2: connect-redis github

yarn add redis connect-redis express-session

Example 3: node-redis

// node-redis to promise, because node-redis not support promise

import bluebird from 'bluebird'
import { Commands, createClient } from 'redis'

const client = createClient({
	host: process.env.REDIS_HOST,
	port: parseInt(process.env.REDIS_PORT),
	password: process.env.REDIS_PASSWORD
})

let redisCon: Commands<any>
;(async (redis) => {
	const redisPromise = await bluebird.resolve<Commands<any>>(redis)
	redisCon = redisPromise
})(client)

export { redisCon }

Example 4: nodejs redis setex

async function upsert(table, data) {
  let key = table;
  if (data && data.id) {
    key = key + '_' + data.id;
  }

  client.setex(key, 10, JSON.stringify(data));
  return true;
}