Skip to content
Download

Cache adapter (Redis)

The CacheAdapter is a small abstraction on top of Bun's native Redis client, focused on:

  • set (permanent or with TTL)
  • get (typed, always returns an object)
  • exists
  • remove

Import

ts
import { CacheAdapter } from "@grupodiariodaregiao/bunstone";

Setup

By default it uses Bun's global redis client (reads REDIS_URL / VALKEY_URL).

ts
const cache = new CacheAdapter();

Or pass a custom connection URL:

ts
const cache = new CacheAdapter({ url: "redis://localhost:6379" });

Set

ts
await cache.set("user:1", { id: 1, name: "Alice" }, { permanent: true });
await cache.set("session:123", { userId: 1 }, { ttlSeconds: 60 * 60 }); // 1 hour

Get (typed)

get<T>() parses JSON automatically and always returns an object (if the key is missing, it returns {}).

ts
type UserCache = { id: number; name: string };
const user = await cache.get<UserCache>("user:1");

Exists / Remove

ts
const exists = await cache.exists("user:1");
await cache.remove("user:1");

Practical Example

See how to use the Cache Adapter in a controller:

ts
import {
  Module,
  Controller,
  Post,
  Get,
  AppStartup,
  CacheAdapter,
  FormData,
} from "../../index";

@Controller("cache")
class CacheController {
  constructor(private readonly cache: CacheAdapter) {}

  @Get(":key")
  async getCache(key: string) {
    const value = await this.cache.get(key);
    return { key, value };
  }

  @Post(":key")
  async setCache(key: string, @Body() body: any) {
    await this.cache.set(key, body, { ttlSeconds: 60 });
    return { success: true };
  }
}

@Controller("upload")
class UploadController {
  @Post()
  async uploadFile(@FormData() formData: any) {
    // Access form fields and files
    const { fields, files } = formData;
    return {
      receivedFields: Object.keys(fields),
      receivedFiles: Object.keys(files),
    };
  }
}

@Module({
  controllers: [CacheController, UploadController],
  providers: [CacheAdapter],
})
class AppModule {}

const app = await AppStartup.create(AppModule);
console.log("Adapters example configured.");

See it on GitHub

Released under the MIT License.