Redis Provider

This provider wires the official redis package to REDIS_URL, validates the URL with Zod, and includes small setCache / getCache / deleteCache helpers.

Features

  • Zod-validated REDIS_URL
  • createClient configured from env
  • Optional TTL helpers for string keys (seconds or milliseconds)
  • MVC and Feature architecture variants

Installation Guide

npx servercn-cli add pr redis

File Structure

  • src/configs/env.ts
  • src/configs/redis.ts
  • src/shared/configs/env.ts
  • src/shared/configs/redis.ts

Environment Configuration

src/configs/env.ts
/* eslint-disable no-console */
import "dotenv-flow/config";
import { z } from "zod";
 
export const envSchema = z.object({
  REDIS_URL: z.url()
});
 
export type Env = z.infer<typeof envSchema>;
 
const result = envSchema.safeParse(process.env);
 
if (!result.success) {
  console.error("❌ Invalid environment configuration");
  console.error(z.treeifyError(result.error));
  process.exit(1);
}
 
export const env: Readonly<Env> = Object.freeze(result.data);
 
export default env;

Redis client and cache helpers

src/configs/redis.ts
import { createClient } from "redis";
import { env } from "./env.ts";
 
const redisClient = createClient({
  url: env.REDIS_URL
});
 
export default redisClient;
 
export const setCache = async (
  key: string,
  value: string,
  expireInSeconds?: number,
  expireInMS?: number
) => {
  if (expireInSeconds) {
    await redisClient.set(key, value, {
      expiration: {
        type: "EX",
        value: expireInSeconds
      }
    });
  } else if (expireInMS) {
    await redisClient.set(key, value, {
      expiration: {
        type: "PX",
        value: expireInMS
      }
    });
  } else {
    await redisClient.set(key, value);
  }
};
 
export const getCache = async (key: string) => {
  return await redisClient.get(key);
};
 
export const deleteCache = async (key: string) => {
  return await redisClient.del(key);
};

Usage

Connect the client when your app boots (after importing the module so the client exists), then use the helpers or the raw client.

import redisClient, { setCache, getCache } from "./configs/redis";
 
await redisClient.connect();
 
await setCache("otp:123", "987654", 300);
const otp = await getCache("otp:123");

The template includes inline comment examples for OTP-style keys at the bottom of redis.ts.

Example .env

REDIS_URL=redis://localhost:6379

File & Folder Structure

Loading files...

Installation

npx servercn-cli add provider redis