export function lazy<T>(factory: () => T): () => T {
let cached: T | undefined;
let initialized = false;
return () => {
if (!initialized) {
cached = factory();
initialized = true;
}
return cached as T;
};
}
// Module-scoped lazy singleton — DB connection
const getDb = lazy(() => {
console.log('Connecting to DB…'); // logged exactly once
return new DatabaseClient(process.env.DATABASE_URL!);
});
// Anywhere in the codebase:
const db = getDb(); // first call: opens connection
const db2 = getDb(); // subsequent calls: returns the same instance
Create a free account and build your private vault. Share publicly whenever you want.