feat: scope-aware async (transport-agnostic) DI container
This commit is contained in:
2 files changed
+50
No files matched your search
@@ -0,0 +1,27 @@
|
||||
export type Scope = 'app' | 'request';
|
||||
export type Factory = (ctx: Record<string, unknown>) => unknown | Promise<unknown>;
|
||||
|
||||
interface Binding { scope: Scope; factory: Factory; cached?: unknown; resolved?: boolean }
|
||||
|
||||
export class Container {
|
||||
private readonly bindings = new Map<string, Binding>();
|
||||
|
||||
register(token: string, scope: Scope, factory: Factory): void {
|
||||
this.bindings.set(token, { scope, factory });
|
||||
}
|
||||
|
||||
has(token: string): boolean {
|
||||
return this.bindings.has(token);
|
||||
}
|
||||
|
||||
// ponytail: app-scope memoizes; request-scope always re-runs. resolve is async
|
||||
// so a future remote transport (mesh) slots in without changing callers.
|
||||
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
|
||||
const b = this.bindings.get(token);
|
||||
if (!b) throw new Error(`unknown token: ${token}`);
|
||||
if (b.scope === 'app' && b.resolved) return b.cached;
|
||||
const value = await b.factory(ctx);
|
||||
if (b.scope === 'app') { b.cached = value; b.resolved = true; }
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { expect, test, vi } from 'vitest';
|
||||
import { Container } from '../src/container';
|
||||
|
||||
test('app-scoped factory is memoized (runs once)', async () => {
|
||||
const c = new Container();
|
||||
const factory = vi.fn(async () => ({ db: 'connected' }));
|
||||
c.register('db', 'app', factory);
|
||||
const a = await c.resolve('db');
|
||||
const b = await c.resolve('db');
|
||||
expect(a).toBe(b);
|
||||
expect(factory).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('resolve is async even for sync factories', async () => {
|
||||
const c = new Container();
|
||||
c.register('cfg', 'app', () => ({ port: 3000 }));
|
||||
await expect(c.resolve('cfg')).resolves.toEqual({ port: 3000 });
|
||||
});
|
||||
|
||||
test('resolve throws a clear error for an unknown token', async () => {
|
||||
const c = new Container();
|
||||
await expect(c.resolve('missing')).rejects.toThrow(/unknown token: missing/);
|
||||
});
|
||||
Reference in new issue
Block a user