A powerful and type-safe singleton manager for TypeScript/JavaScript applications.
Singleton Manager provides a centralized way to manage singleton instances in your application. It ensures that only one instance of each registered class exists throughout the application lifecycle, with full TypeScript support and type safety.
bun add @nowarajs/singleton-manager
import { SingletonManager } from '@nowarajs/singleton-manager';
// Define your singleton class
class DatabaseConnection {
private _isConnected = false;
public constructor() {
console.log('Database connection created');
this._isConnected = true;
}
public get isConnected(): boolean {
return this._isConnected;
}
public query(sql: string): string[] {
console.log(`Executing query: ${sql}`);
return ['result1', 'result2'];
}
}
// Register the singleton
SingletonManager.register('DatabaseConnection', DatabaseConnection);
// Get the singleton instance (same instance every time)
const db1 = SingletonManager.get<DatabaseConnection>('DatabaseConnection');
const db2 = SingletonManager.get<DatabaseConnection>('DatabaseConnection');
console.log(db1 === db2); // true - same instance
class ApiClient {
private readonly _baseUrl: string;
private readonly _apiKey: string;
public constructor(baseUrl: string, apiKey: string) {
this._baseUrl = baseUrl;
this._apiKey = apiKey;
}
public get baseUrl(): string {
return this._baseUrl;
}
}
// Register with constructor arguments
SingletonManager.register(
'ApiClient',
ApiClient,
'https://api.example.com',
'your-api-key'
);
// Use the singleton
const client = SingletonManager.get<ApiClient>('ApiClient');
console.log(client.baseUrl); // https://api.example.com
// TypeScript provides full type safety
const dbConnection = SingletonManager.get<DatabaseConnection>('DatabaseConnection');
dbConnection.query('SELECT * FROM users'); // โ
TypeScript knows this method exists
// Attempting to call non-existent methods will cause TypeScript errors
// dbConnection.nonExistentMethod(); // โ TypeScript error
// Check if a singleton is registered
if (SingletonManager.has('DatabaseConnection')) {
const db = SingletonManager.get<DatabaseConnection>('DatabaseConnection');
}
// Unregister a singleton (removes the instance)
SingletonManager.unregister('DatabaseConnection');
// Re-register will create a new instance
SingletonManager.register('DatabaseConnection', DatabaseConnection);
You can find the complete API reference documentation for TypedEventEmitter
at:
Distributed under the MIT License. See LICENSE for more information.
NowaraJS Team