rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Start from the template. src/app.service.ts and src/app.controller.ts stay as they are.

Install#

Nothing: RedisClient is part of Bun.

The client is created at startup#

A small module builds the client once at startup and closes it on shutdown with the register cleanup, which runs when the app is stopped.

TypeScript
// src/redis.ts
import { Rhythm, decorate } from "@rhythmjs/rhythm";
import { RedisClient } from "bun";

export const redisModule = new Rhythm({ name: "redis" }).register(
  decorate(() => ({ redis: new RedisClient(process.env.REDIS_URL ?? "redis://localhost:6379") })),
  ({ redis }) => redis.close(),
);

The app includes this module and main.ts calls appModule.stop() on shutdown, so Rhythm closes the client for you.

A service holds the data#

A plain in-memory service stands in for a slow database. loads counts how often it was really read.

TypeScript
// src/products/products.service.ts
export interface Product {
  id: string;
  name: string;
  price: number;
}

export const productsService = {
  loads: 0,
  products: new Map<string, Product>([
    ["1", { id: "1", name: "Keyboard", price: 49 }],
    ["2", { id: "2", name: "Mouse", price: 25 }],
  ]),

  async get(id: string): Promise<Product | undefined> {
    this.loads++;
    await Bun.sleep(50);
    return this.products.get(id);
  },

  update(id: string, input: { name?: string; price?: number }): Product | undefined {
    const product = this.products.get(id);
    if (!product) return undefined;
    const next = { ...product, ...input };
    this.products.set(id, next);
    return next;
  },
};

The controller caches#

This is the products controller, a RhythmRouter with full /products/... paths. GET /products/:id is cache-aside: look in Redis, load on a miss, store with an expiry. PATCH /products/:id deletes the key, so the next read refreshes the cache.

TypeScript
// src/products/products.controller.ts
import { RhythmRouter } from "@rhythmjs/router";
import type { RhythmHttpContext } from "@rhythmjs/router/context";
import type { RedisClient } from "bun";
import type { productsService } from "./products.service";
import { error, json } from "@rhythmjs/router/response";

export type ProductsContext = RhythmHttpContext & {
  redis: RedisClient;
  productsService: typeof productsService;
};

const TTL_SECONDS = 60;
const cacheKey = (id: string) => `product:${id}`;

export const productsController = new RhythmRouter<ProductsContext>()
  .get("/products/:id", async (ctx) => {
    const key = cacheKey(ctx.params.id);

    const hit = await ctx.redis.get(key);
    if (hit !== null) {
      ctx.response.headers.set("x-cache", "hit");
      json(ctx, JSON.parse(hit));
      return;
    }

    const product = await ctx.productsService.get(ctx.params.id);
    if (!product) {
      error(ctx, 404, "Product not found");
      return;
    }

    await ctx.redis.set(key, JSON.stringify(product));
    await ctx.redis.expire(key, TTL_SECONDS);
    ctx.response.headers.set("x-cache", "miss");
    json(ctx, product);
  })
  .patch("/products/:id", async (ctx) => {
    const { name, price } = (await ctx.request.json()) as { name?: string; price?: number };
    if (price !== undefined && (typeof price !== "number" || price < 0)) {
      error(ctx, 400, "price must be a non-negative number");
      return;
    }

    const product = ctx.productsService.update(ctx.params.id, { name, price });
    if (!product) {
      error(ctx, 404, "Product not found");
      return;
    }

    await ctx.redis.del(cacheKey(ctx.params.id));
    json(ctx, product);
  });

The products module owns the service#

A module that provides the service on its startup context. The app picks what it needs from it with include.

TypeScript
// src/products/products.module.ts
import { Rhythm, decorate } from "@rhythmjs/rhythm";
import { productsService } from "./products.service";

export const productsModule = new Rhythm({ name: "products" }).register(decorate(() => ({ productsService })));

Assemble the app#

The app includes the redis and products modules, picking redis and productsService into its startup context, and mounts the controllers. The controller's ProductsContext is checked against that context when it is mounted: leave out the redis pick and it no longer compiles.

TypeScript
// src/app.module.ts
import { Rhythm, decorate, include, mount } from "@rhythmjs/rhythm";
import { appController } from "./app.controller";
import { appService } from "./app.service";
import { productsController } from "./products/products.controller";
import { productsModule } from "./products/products.module";
import { redisModule } from "./redis";

export const appModule = new Rhythm({ name: "app" })
  .register(include(redisModule, ({ redis }) => ({ redis })))
  .register(include(productsModule, ({ productsService }) => ({ productsService })))
  .register(decorate(() => ({ appService })))
  .use(mount(productsController))
  .use(mount(appController));

main.ts serves the app and stops it on SIGINT, which closes the client:

TypeScript
// src/main.ts
import { toFetchHandler } from "@rhythmjs/router/fetch";
import { appModule } from "./app.module";

const port = Number(process.env.PORT ?? 3011);

const server = Bun.serve({ port, fetch: toFetchHandler(appModule) });
console.log(`listening on ${server.url}`);

process.on("SIGINT", async () => {
  await server.stop();
  await appModule.stop();
  process.exit(0);
});

Things to check#

  • Treat a cache failure as a miss: catch errors around get and fall through to the source.
  • One client per process; never one per request.

The full app, with tests, is examples/redis, built from the template.