inversify-typesafe-spring-like 0.5.5 → 0.5.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +242 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -84,6 +84,24 @@ const getArticleUseCase = applicationContext.get("GetArticleUseCase")
|
|
|
84
84
|
getArticleUseCase.execute(1).then(console.log)
|
|
85
85
|
```
|
|
86
86
|
|
|
87
|
+
## TL;DR
|
|
88
|
+
|
|
89
|
+
`inversify-typesafe-spring-like` is a Spring-flavored add-on for `inversify-typesafe`. Define a `Beans` map, register every bean with `BeanConfig`, create an `Autowired` decorator with `returnAutowired`, and initialize the container with `ApplicationContext`. Bean names are checked and return types are inferred at compile time, while beans use singleton scope by default.
|
|
90
|
+
|
|
91
|
+
<details>
|
|
92
|
+
<summary><strong>For AI Agents Using This Library</strong></summary>
|
|
93
|
+
|
|
94
|
+
- Define one `Beans` map whose string keys are bean names and whose values are the types returned for those names.
|
|
95
|
+
- Declare a `BeanConfig<Beans>` containing every key in `Beans`, and bind each key to a compatible implementation with the provided `bind()` function.
|
|
96
|
+
- Create a project-local decorator by destructuring `const { Autowired } = returnAutowired<Beans>()`, then use `@Autowired("BeanName")` for constructor injection.
|
|
97
|
+
- Pass the bean config to `ApplicationContext`; let TypeScript infer the context type instead of adding a generic argument manually.
|
|
98
|
+
- Resolve beans with `applicationContext.get("BeanName")`. Do not cast bean names or result types, because doing so bypasses compile-time checks.
|
|
99
|
+
- Assume singleton scope unless an explicit `ContainerOptions` argument passed to `ApplicationContext` overrides `defaultScope`.
|
|
100
|
+
- Use the underlying `inversify-typesafe` capabilities for advanced bindings and the original InversifyJS API. `BeanConfig`, `ApplicationContext`, and `returnAutowired` correspond to `TypesafeServiceConfig`, `createTypesafeContainer`, and `returnTypesafeInject` respectively.
|
|
101
|
+
- Keep the `Beans` map, bean config, `get` calls, and `Autowired` decorators synchronized whenever a bean is added, removed, or renamed.
|
|
102
|
+
|
|
103
|
+
</details>
|
|
104
|
+
|
|
87
105
|
## Introduction
|
|
88
106
|
|
|
89
107
|
This library extends [inversify-typesafe](https://github.com/myeongjae-kim/inversify-typesafe) to provide a development experience similar to [Spring Framework](https://spring.io/).
|
|
@@ -128,6 +146,229 @@ The API is designed to mirror Spring's terminology:
|
|
|
128
146
|
|
|
129
147
|
For complete usage documentation and advanced features, please refer to the [inversify-typesafe documentation](https://github.com/myeongjae-kim/inversify-typesafe/tree/main?tab=readme-ov-file#usage).
|
|
130
148
|
|
|
149
|
+
## Advanced Patterns
|
|
150
|
+
|
|
151
|
+
### Lazy ApplicationContext Initialization
|
|
152
|
+
|
|
153
|
+
In production applications, you may want to defer the initialization of the ApplicationContext until it's actually needed. This is especially useful in serverless environments or when you want to avoid initialization overhead during module loading.
|
|
154
|
+
|
|
155
|
+
**The `lazy` utility function:**
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
// core/common/util/lazy.ts
|
|
159
|
+
export const lazy = <T>(fn: () => T) => {
|
|
160
|
+
let value: T | undefined;
|
|
161
|
+
return () => value ?? (value = fn());
|
|
162
|
+
};
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
**Usage with ApplicationContext:**
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
// core/config/applicationContext.ts
|
|
169
|
+
import 'reflect-metadata';
|
|
170
|
+
import { ApplicationContext } from 'inversify-typesafe-spring-like';
|
|
171
|
+
import { beanConfig } from './beanConfig';
|
|
172
|
+
import { lazy } from '../common/util/lazy';
|
|
173
|
+
|
|
174
|
+
// Lazy initialization - ApplicationContext is created only when first accessed
|
|
175
|
+
export const applicationContext = lazy(() => ApplicationContext(beanConfig));
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
**Using in controllers or services:**
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
// app/api/articles/GetArticleController.ts
|
|
182
|
+
import { applicationContext } from '@/core/config/applicationContext';
|
|
183
|
+
|
|
184
|
+
export default async function handler(req: Request) {
|
|
185
|
+
// ApplicationContext is initialized on first call, then reused
|
|
186
|
+
const useCase = applicationContext().get("GetArticleUseCase");
|
|
187
|
+
const article = await useCase.execute(req.params.id);
|
|
188
|
+
return Response.json(article);
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
**Why use lazy initialization?**
|
|
193
|
+
|
|
194
|
+
| Benefit | Description |
|
|
195
|
+
|---------|-------------|
|
|
196
|
+
| Faster cold starts | Module loading doesn't trigger DI container initialization |
|
|
197
|
+
| On-demand creation | Container is only created when actually needed |
|
|
198
|
+
| Singleton guarantee | Multiple calls return the same instance |
|
|
199
|
+
| Testability | Easy to mock or replace in tests |
|
|
200
|
+
|
|
201
|
+
**Without lazy (eager initialization):**
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
// ❌ Container is created immediately when module is imported
|
|
205
|
+
export const applicationContext = ApplicationContext(beanConfig);
|
|
206
|
+
|
|
207
|
+
// Every import of this module triggers initialization
|
|
208
|
+
import { applicationContext } from './applicationContext';
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
**With lazy (deferred initialization):**
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
// ✅ Container is created only when applicationContext() is called
|
|
215
|
+
export const applicationContext = lazy(() => ApplicationContext(beanConfig));
|
|
216
|
+
|
|
217
|
+
// Import doesn't trigger initialization
|
|
218
|
+
import { applicationContext } from './applicationContext';
|
|
219
|
+
|
|
220
|
+
// Initialization happens here, on first use
|
|
221
|
+
const useCase = applicationContext().get("GetArticleUseCase");
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
**Note:** The `lazy` function ensures the initialization function is called exactly once, and subsequent calls return the cached value.
|
|
225
|
+
|
|
226
|
+
### Domain-Specific BeanConfig
|
|
227
|
+
|
|
228
|
+
As your application grows, you may want to organize beans by domain. This pattern allows each domain module to define its own beans while extending a common configuration.
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
// core/config/CommonBeanConfig.ts
|
|
232
|
+
import { BeanConfig } from "inversify-typesafe-spring-like";
|
|
233
|
+
|
|
234
|
+
interface LoggingPort {
|
|
235
|
+
log(message: string): void;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
class ConsoleLogger implements LoggingPort {
|
|
239
|
+
log(message: string): void {
|
|
240
|
+
console.log(`[LOG] ${message}`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export type CommonBeans = {
|
|
245
|
+
LoggingPort: LoggingPort;
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
export const commonBeanConfig: BeanConfig<CommonBeans> = {
|
|
249
|
+
LoggingPort: (bind) => bind().to(ConsoleLogger),
|
|
250
|
+
};
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
// core/article/config/ArticleBeanConfig.ts
|
|
255
|
+
import { BeanConfig, returnAutowired } from "inversify-typesafe-spring-like";
|
|
256
|
+
import { CommonBeans, commonBeanConfig } from "../config/CommonBeanConfig";
|
|
257
|
+
|
|
258
|
+
interface ArticleQueryPort { /* ... */ }
|
|
259
|
+
interface ArticleCommandPort { /* ... */ }
|
|
260
|
+
interface GetArticleUseCase { /* ... */ }
|
|
261
|
+
|
|
262
|
+
// Extend CommonBeans with domain-specific beans
|
|
263
|
+
export type ArticleBeans = CommonBeans & {
|
|
264
|
+
ArticleQueryPort: ArticleQueryPort;
|
|
265
|
+
ArticleCommandPort: ArticleCommandPort;
|
|
266
|
+
GetArticleUseCase: GetArticleUseCase;
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
// Domain-specific Autowired decorator
|
|
270
|
+
export const { Autowired: ArticleAutowired } = returnAutowired<ArticleBeans>();
|
|
271
|
+
|
|
272
|
+
export const articleBeanConfig: BeanConfig<ArticleBeans> = {
|
|
273
|
+
...commonBeanConfig, // Include common beans
|
|
274
|
+
ArticleQueryPort: (bind) => bind().to(ArticlePersistenceAdapter),
|
|
275
|
+
ArticleCommandPort: (bind) => bind().to(ArticlePersistenceAdapter),
|
|
276
|
+
GetArticleUseCase: (bind) => bind().to(ArticleQueryService),
|
|
277
|
+
};
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
// Usage in domain service
|
|
282
|
+
class ArticleQueryService implements GetArticleUseCase {
|
|
283
|
+
constructor(
|
|
284
|
+
@ArticleAutowired("ArticleQueryPort") // Type-safe within ArticleBeans
|
|
285
|
+
private readonly articleQueryPort: ArticleQueryPort,
|
|
286
|
+
@ArticleAutowired("LoggingPort") // Common beans are also available
|
|
287
|
+
private readonly loggingPort: LoggingPort,
|
|
288
|
+
) { }
|
|
289
|
+
}
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
**Benefits:**
|
|
293
|
+
- Each domain owns its bean configuration
|
|
294
|
+
- Common beans (logging, transactions, etc.) are shared across domains
|
|
295
|
+
- Type safety is maintained within each domain's scope
|
|
296
|
+
- Easy to identify which beans belong to which domain
|
|
297
|
+
|
|
298
|
+
### Reusing a Single Class for Multiple Interfaces with `toResolvedValue`
|
|
299
|
+
|
|
300
|
+
When a single class implements multiple interfaces (e.g., both `QueryPort` and `CommandPort`), you can use `toResolvedValue` to register the same instance under different bean names. This avoids creating separate instances and ensures consistency.
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
import { ApplicationContext, BeanConfig, returnAutowired } from "inversify-typesafe-spring-like";
|
|
304
|
+
|
|
305
|
+
// Interfaces
|
|
306
|
+
interface StayQueryPort {
|
|
307
|
+
findById(id: number): Promise<Stay | null>;
|
|
308
|
+
findAll(): Promise<Stay[]>;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
interface StayCommandPort {
|
|
312
|
+
save(stay: Stay): Promise<Stay>;
|
|
313
|
+
delete(id: number): Promise<void>;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Single class implementing both interfaces
|
|
317
|
+
class StayPersistenceAdapter implements StayQueryPort, StayCommandPort {
|
|
318
|
+
async findById(id: number): Promise<Stay | null> { /* ... */ }
|
|
319
|
+
async findAll(): Promise<Stay[]> { /* ... */ }
|
|
320
|
+
async save(stay: Stay): Promise<Stay> { /* ... */ }
|
|
321
|
+
async delete(id: number): Promise<void> { /* ... */ }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
type Beans = {
|
|
325
|
+
StayQueryPort: StayQueryPort;
|
|
326
|
+
StayCommandPort: StayCommandPort;
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
const { Autowired } = returnAutowired<Beans>();
|
|
330
|
+
|
|
331
|
+
const beanConfig: BeanConfig<Beans> = {
|
|
332
|
+
// Register the class for the first interface
|
|
333
|
+
StayQueryPort: (bind) => bind().to(StayPersistenceAdapter),
|
|
334
|
+
|
|
335
|
+
// Reuse the same instance for the second interface
|
|
336
|
+
StayCommandPort: (bind) =>
|
|
337
|
+
bind().toResolvedValue(
|
|
338
|
+
(queryPort) => queryPort as StayCommandPort, // Transform function
|
|
339
|
+
['StayQueryPort'] // Dependencies to resolve first
|
|
340
|
+
),
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
const applicationContext = ApplicationContext(beanConfig);
|
|
344
|
+
|
|
345
|
+
// Both return the same instance
|
|
346
|
+
const queryPort = applicationContext.get("StayQueryPort");
|
|
347
|
+
const commandPort = applicationContext.get("StayCommandPort");
|
|
348
|
+
|
|
349
|
+
console.log(queryPort === commandPort); // true (same instance)
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
**How `toResolvedValue` works:**
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
bind().toResolvedValue(transformFn, dependencies)
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
- `transformFn`: A function that receives the resolved dependencies and returns the value to bind
|
|
359
|
+
- `dependencies`: An array of bean names to resolve before calling the transform function
|
|
360
|
+
|
|
361
|
+
**Use cases:**
|
|
362
|
+
- Single class implementing multiple interfaces (CQRS pattern)
|
|
363
|
+
- Creating derived beans from existing beans
|
|
364
|
+
- Aliasing beans under different names
|
|
365
|
+
- Lazy transformation of resolved dependencies
|
|
366
|
+
|
|
367
|
+
**Benefits:**
|
|
368
|
+
- Avoids duplicate instances when the same class serves multiple roles
|
|
369
|
+
- Maintains singleton behavior across interface boundaries
|
|
370
|
+
- Clear dependency declaration for complex wiring scenarios
|
|
371
|
+
|
|
131
372
|
## License
|
|
132
373
|
|
|
133
|
-
MIT © [Myeongjae Kim](https://myeongjae.kim)
|
|
374
|
+
MIT © [Myeongjae Kim](https://myeongjae.kim)
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import { ContainerOptions } from \"inversify\";\nimport { TypesafeServiceConfig as BeanConfig, createTypesafeContainer, returnTypesafeInject } from \"inversify-typesafe\";\n\nexport const returnAutowired = <S extends Record<string, unknown>>()
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import { ContainerOptions } from \"inversify\";\nimport { TypesafeServiceConfig as BeanConfig, createTypesafeContainer, returnTypesafeInject, TypesafeContainer } from \"inversify-typesafe\";\n\nexport const returnAutowired = <S extends Record<string, unknown>>(): { Autowired: ReturnType<typeof returnTypesafeInject<S>> } =>\n ({ Autowired: returnTypesafeInject<S>() });\n\nexport type { BeanConfig };\n\nexport const ApplicationContext = <S extends Record<string, unknown>>(beanConfig: BeanConfig<S>, options?: ContainerOptions): TypesafeContainer<S> =>\n createTypesafeContainer(beanConfig, { defaultScope: \"Singleton\", ...options });"],"names":["beanConfig","options","createTypesafeContainer","_extends","defaultScope","Autowired","returnTypesafeInject"],"mappings":"uRAQkC,SAAoCA,EAA2BC,GAC/F,OAAAC,EAAuBA,wBAACF,EAAUG,EAAIC,CAAAA,aAAc,aAAgBH,GAAU,0BANjD,WAAH,MACzB,CAAEI,UAAWC,EAAAA,uBAA2B"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ContainerOptions } from "inversify";
|
|
2
|
-
import { TypesafeServiceConfig as BeanConfig } from "inversify-typesafe";
|
|
2
|
+
import { TypesafeServiceConfig as BeanConfig, returnTypesafeInject, TypesafeContainer } from "inversify-typesafe";
|
|
3
3
|
export declare const returnAutowired: <S extends Record<string, unknown>>() => {
|
|
4
|
-
Autowired:
|
|
4
|
+
Autowired: ReturnType<typeof returnTypesafeInject<S>>;
|
|
5
5
|
};
|
|
6
6
|
export type { BeanConfig };
|
|
7
|
-
export declare const ApplicationContext: <S extends Record<string, unknown>>(beanConfig: BeanConfig<S>, options?: ContainerOptions) =>
|
|
7
|
+
export declare const ApplicationContext: <S extends Record<string, unknown>>(beanConfig: BeanConfig<S>, options?: ContainerOptions) => TypesafeContainer<S>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ContainerOptions } from "inversify";
|
|
2
|
-
import { TypesafeServiceConfig as BeanConfig } from "inversify-typesafe";
|
|
2
|
+
import { TypesafeServiceConfig as BeanConfig, returnTypesafeInject, TypesafeContainer } from "inversify-typesafe";
|
|
3
3
|
export declare const returnAutowired: <S extends Record<string, unknown>>() => {
|
|
4
|
-
Autowired:
|
|
4
|
+
Autowired: ReturnType<typeof returnTypesafeInject<S>>;
|
|
5
5
|
};
|
|
6
6
|
export type { BeanConfig };
|
|
7
|
-
export declare const ApplicationContext: <S extends Record<string, unknown>>(beanConfig: BeanConfig<S>, options?: ContainerOptions) =>
|
|
7
|
+
export declare const ApplicationContext: <S extends Record<string, unknown>>(beanConfig: BeanConfig<S>, options?: ContainerOptions) => TypesafeContainer<S>;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { ContainerOptions } from \"inversify\";\nimport { TypesafeServiceConfig as BeanConfig, createTypesafeContainer, returnTypesafeInject } from \"inversify-typesafe\";\n\nexport const returnAutowired = <S extends Record<string, unknown>>()
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { ContainerOptions } from \"inversify\";\nimport { TypesafeServiceConfig as BeanConfig, createTypesafeContainer, returnTypesafeInject, TypesafeContainer } from \"inversify-typesafe\";\n\nexport const returnAutowired = <S extends Record<string, unknown>>(): { Autowired: ReturnType<typeof returnTypesafeInject<S>> } =>\n ({ Autowired: returnTypesafeInject<S>() });\n\nexport type { BeanConfig };\n\nexport const ApplicationContext = <S extends Record<string, unknown>>(beanConfig: BeanConfig<S>, options?: ContainerOptions): TypesafeContainer<S> =>\n createTypesafeContainer(beanConfig, { defaultScope: \"Singleton\", ...options });"],"names":["returnAutowired","Autowired","returnTypesafeInject","ApplicationContext","beanConfig","options","createTypesafeContainer","_extends","defaultScope"],"mappings":"+SAGa,MAAAA,EAAkBA,KAC5B,CAAEC,UAAWC,MAIHC,EAAqBA,CAAoCC,EAA2BC,IAC/FC,EAAwBF,EAAUG,GAAIC,aAAc,aAAgBH"}
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/index.ts"],"sourcesContent":["import { ContainerOptions } from \"inversify\";\nimport { TypesafeServiceConfig as BeanConfig, createTypesafeContainer, returnTypesafeInject } from \"inversify-typesafe\";\n\nexport const returnAutowired = <S extends Record<string, unknown>>()
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/index.ts"],"sourcesContent":["import { ContainerOptions } from \"inversify\";\nimport { TypesafeServiceConfig as BeanConfig, createTypesafeContainer, returnTypesafeInject, TypesafeContainer } from \"inversify-typesafe\";\n\nexport const returnAutowired = <S extends Record<string, unknown>>(): { Autowired: ReturnType<typeof returnTypesafeInject<S>> } =>\n ({ Autowired: returnTypesafeInject<S>() });\n\nexport type { BeanConfig };\n\nexport const ApplicationContext = <S extends Record<string, unknown>>(beanConfig: BeanConfig<S>, options?: ContainerOptions): TypesafeContainer<S> =>\n createTypesafeContainer(beanConfig, { defaultScope: \"Singleton\", ...options });"],"names":["beanConfig","options","createTypesafeContainer","_extends","defaultScope","Autowired","returnTypesafeInject"],"mappings":"2iBAQkC,SAAoCA,EAA2BC,GAC/F,OAAAC,EAAuBA,wBAACF,EAAUG,EAAIC,CAAAA,aAAc,aAAgBH,GAAU,oBANjD,WAAH,MACzB,CAAEI,UAAWC,EAAAA,uBAA2B"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "inversify-typesafe-spring-like",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.5.
|
|
4
|
+
"version": "0.5.6",
|
|
5
5
|
"description": "Add-On Library for inversify-typesafe to make it more like Spring.",
|
|
6
6
|
"source": "src/index.ts",
|
|
7
7
|
"exports": {
|
|
@@ -61,6 +61,7 @@
|
|
|
61
61
|
"author": "Myeongjae Kim",
|
|
62
62
|
"license": "MIT",
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"inversify
|
|
64
|
+
"inversify": "^7.10.8",
|
|
65
|
+
"inversify-typesafe": "^0.5.6"
|
|
65
66
|
}
|
|
66
67
|
}
|