Hedystia 1.8: Subscription Lifecycle & Connection Management
Robust real-time infrastructure with automatic disconnection handling. Track subscriber lifecycles, detect stale connections, and ensure clean resource cleanup.
// server.ts
import Hedystia, { h } from "hedystia";
export const app = new Hedystia()
.onSubscriptionOpen((ctx) => {
console.log(`[${ctx.path}] Client connected: ${ctx.subscriptionId}`);
})
.onSubscriptionClose((ctx) => {
console.log(`[${ctx.path}] Client disconnected: ${ctx.reason}`);
})
.subscription(
"/dashboard/:teamId",
async (ctx) => {
const sendMetrics = () => {
if (!ctx.isActive()) return;
ctx.sendData({
activeUsers: 42,
cpuUsage: Math.random() * 100,
memoryUsage: Math.random() * 100,
timestamp: Date.now(),
});
};
sendMetrics();
const interval = setInterval(sendMetrics, 5000);
ctx.ws.addEventListener?.("close", () => clearInterval(interval));
},
{
params: h.object({ teamId: h.string() }),
data: h.object({
activeUsers: h.number(),
cpuUsage: h.number(),
memoryUsage: h.number(),
timestamp: h.number(),
}),
}
)
.listen(3000);
// client.ts
import { createClient } from "@hedystia/client";
import type { app } from "./server";
const client = createClient<typeof app>("http://localhost:3000");
const { unsubscribe } = client.dashboard.teamId("engineering").subscribe(({ data, _error }) => {
if (data) {
console.log(`📊 Metrics: ${data.activeUsers} users, CPU ${data.cpuUsage.toFixed(1)}%`);
}
});
process.on("SIGINT", () => unsubscribe());
GitHub: https://github.com/Hedystia/Framework
npm: https://www.npmjs.com/package/hedystia