javascript / expert
Snippet
The Registry Pattern for Decoupled Service Injection
The Registry Pattern decouples the consumption of services from their concrete implementation. This is particularly useful in complex Next.js applications where services like Auth or Database need to be mocked for testing or swapped based on the environment.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type ServiceMap = Record<string, any>;class ServiceRegistry<T extends ServiceMap> {private instances = new Map<keyof T, T[keyof T]>();register<K extends keyof T>(key: K, instance: T[K]): void {this.instances.set(key, instance);}get<K extends keyof T>(key: K): T[K] {const instance = this.instances.get(key);if (!instance) throw new Error(`Service ${String(key)} not found`);return instance as T[K];}}const registry = new ServiceRegistry<{ auth: AuthService; db: Database }>();
nextjs
Breakdown
1
private instances = new Map<keyof T, T[keyof T]>();
Type-safe storage for service instances indexed by their keys.
2
get<K extends keyof T>(key: K): T[K]
Retrieves a service with full type inference based on the provided key.
3
return instance as T[K];
Casts the retrieved instance back to its specific type defined in the ServiceMap.