decorator-dependency-injection 1.0.0

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.
@@ -0,0 +1,31 @@
1
+ # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
2
+ # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
3
+
4
+ name: Node.js CI
5
+
6
+ on:
7
+ push:
8
+ branches: [ "main" ]
9
+ pull_request:
10
+ branches: [ "main" ]
11
+
12
+ jobs:
13
+ build:
14
+
15
+ runs-on: ubuntu-latest
16
+
17
+ strategy:
18
+ matrix:
19
+ node-version: [18.x, 20.x, 22.x]
20
+ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
21
+
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+ - name: Use Node.js ${{ matrix.node-version }}
25
+ uses: actions/setup-node@v4
26
+ with:
27
+ node-version: ${{ matrix.node-version }}
28
+ cache: 'npm'
29
+ - run: npm ci
30
+ - run: npm run build --if-present
31
+ - run: npm test
@@ -0,0 +1,13 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="WEB_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/.tmp" />
6
+ <excludeFolder url="file://$MODULE_DIR$/temp" />
7
+ <excludeFolder url="file://$MODULE_DIR$/tmp" />
8
+ </content>
9
+ <orderEntry type="inheritedJdk" />
10
+ <orderEntry type="sourceFolder" forTests="false" />
11
+ <orderEntry type="library" name="@types/jest" level="application" />
12
+ </component>
13
+ </module>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="GitToolBoxBlameSettings">
4
+ <option name="version" value="2" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,15 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="GitToolBoxProjectSettings">
4
+ <option name="commitMessageIssueKeyValidationOverride">
5
+ <BoolValueOverride>
6
+ <option name="enabled" value="true" />
7
+ </BoolValueOverride>
8
+ </option>
9
+ <option name="commitMessageValidationEnabledOverride">
10
+ <BoolValueOverride>
11
+ <option name="enabled" value="true" />
12
+ </BoolValueOverride>
13
+ </option>
14
+ </component>
15
+ </project>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="JavaScriptLibraryMappings">
4
+ <file url="file://$PROJECT_DIR$" libraries="{Node.js Core, decorator-depdenency-injection/node_modules}" />
5
+ <file url="file://$PROJECT_DIR$/test" libraries="{@types/jest, Node.js Core, decorator-depdenency-injection/node_modules}" />
6
+ <excludedPredefinedLibrary name="HTML" />
7
+ </component>
8
+ </project>
@@ -0,0 +1,13 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="MaterialThemeProjectNewConfig">
4
+ <option name="metadata">
5
+ <MTProjectMetadataState>
6
+ <option name="migrated" value="true" />
7
+ <option name="pristineConfig" value="false" />
8
+ <option name="userId" value="-1911ddbb:1739357c210:-8000" />
9
+ <option name="version" value="8.13.2" />
10
+ </MTProjectMetadataState>
11
+ </option>
12
+ </component>
13
+ </project>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/decorator-depdenency-injection.iml" filepath="$PROJECT_DIR$/.idea/decorator-depdenency-injection.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
package/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ </component>
6
+ </project>
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Ravi Gairola
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # Decorator Dependency Injection
2
+ [![npm version](https://badge.fury.io/js/decorator-dependency-injection.svg)](http://badge.fury.io/js/decorator-dependency-injection)
3
+ [![Build Status](https://github.com/mallocator/decorator-dependency-injection/actions/workflows/node.js.yml/badge.svg)](https://github.com/mallocator/decorator-dependency-injection/actions/workflows/node.js.yml)
4
+
5
+
6
+ ## Description
7
+
8
+ With TC39 reaching stage 3 on the decorators proposal, it's time to start thinking about how we can use them in our projects. One of the most common patterns in JavaScript is dependency injection. This pattern is used to make our code more testable and maintainable. This library provides simple decorators to help you inject dependencies into your classes and mock them for testing.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install decorator-dependency-injection
14
+ ```
15
+
16
+ Until we reach stage 4, you will need to enable the decorators proposal in your project. You can do this by adding the following babel transpiler options to your `.babelrc` file.
17
+
18
+ ```json
19
+ {
20
+ "plugins": ["@babel/plugin-proposal-decorators"]
21
+ }
22
+ ```
23
+
24
+ To run your project with decorators enabled you will need to use the babel transpiler. You can do this by running the following command in your project root.
25
+
26
+ ```bash
27
+ npx babel-node index.js
28
+ ```
29
+
30
+ Finally, for running tests with decorators enabled you will need to use the babel-jest package. You can do this by adding the following configuration to your `package.json` file.
31
+
32
+ ```json
33
+ {
34
+ "jest": {
35
+ "transform": {
36
+ "^.+\\.jsx?$": "babel-jest"
37
+ }
38
+ }
39
+ }
40
+ ```
41
+
42
+ Other testing frameworks may require a different configuration.
43
+
44
+ For a full example of how to set up a project with decorators, see this project's ```package.json``` file.
45
+
46
+
47
+ ## Usage
48
+
49
+ There are 2 ways of specifying injectable dependencies: ```@Singleton``` and ```@Factory```:
50
+
51
+ ### Singleton
52
+
53
+ The ```@Singleton``` decorator is used to inject a single instance of a dependency into a class. This is useful when you want to share the same instance of a class across multiple classes.
54
+
55
+ ```javascript
56
+ import { Singleton } from 'decorator-dependency-injection';
57
+
58
+ @Singleton
59
+ class Dependency {}
60
+
61
+ class Consumer {
62
+ @Inject(Dependency) dependency // creates an instance only once
63
+ }
64
+ ```
65
+
66
+ ### Factory
67
+
68
+ The ```@Factory``` decorator is used to inject a new instance of a dependency into a class each time it is requested. This is useful when you want to create a new instance of a class each time it is injected.
69
+
70
+ ```javascript
71
+ import { Factory } from 'decorator-dependency-injection';
72
+
73
+ @Factory
74
+ class Dependency {}
75
+
76
+ class Consumer {
77
+ @Inject(Dependency) dependency // creates a new instance each time a new Consumer is created
78
+ }
79
+ ```
80
+
81
+ ## Passing parameters to a dependency
82
+
83
+ You can pass parameters to a dependency by using the ```@Inject``` decorator with a function that returns the dependency.
84
+
85
+ ```javascript
86
+ import { Factory, Inject } from 'decorator-dependency-injection';
87
+
88
+ @Factory
89
+ class Dependency {
90
+ constructor(param1, param2) {
91
+ this.param1 = param1;
92
+ this.param2 = param2;
93
+ }
94
+ }
95
+
96
+ class Consumer {
97
+ @Inject(Dependency, 'myParam', 'myOtherParam') dependency
98
+ }
99
+ ```
100
+
101
+ While this is most useful for Factory dependencies, it can also be used with Singleton dependencies. However, parameters will only be passed to the dependency the first time it is created.
102
+
103
+ ## Mocking dependencies for testing
104
+
105
+ You can mock dependencies by using the ```@Mock``` decorator with a function that returns the mock dependency.
106
+
107
+ ```javascript
108
+ import { Factory, Inject, Mock } from 'decorator-dependency-injection';
109
+
110
+ @Factory
111
+ class Dependency {
112
+ method() {
113
+ return 'real';
114
+ }
115
+ }
116
+
117
+ class Consumer {
118
+ @Inject(Dependency) dependency
119
+
120
+ test() {
121
+ return this.dependency.method();
122
+ }
123
+ }
124
+
125
+ @Mock
126
+ class MockDependency {
127
+ method() {
128
+ return 'mock';
129
+ }
130
+ }
131
+
132
+ const consumer = new Consumer();
133
+
134
+ consumer.test(); // returns 'real'
135
+ ```
136
+
137
+ For more examples, see the tests in the ```test``` directory.
138
+
139
+ ## Running the tests
140
+
141
+ To run the tests, run the following command in the project root.
142
+
143
+ ```bash
144
+ npm test
145
+ ```
@@ -0,0 +1,6 @@
1
+ {
2
+ "presets": ["@babel/preset-env"],
3
+ "plugins": [
4
+ ["@babel/plugin-proposal-decorators", { "version": "2023-11" }]
5
+ ]
6
+ }
package/index.js ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * @typedef {Object} InstanceContext
3
+ * @property {Class} clazz The class of the instance
4
+ * @property {Object} [instance] The instance if it is a singleton
5
+ * @property {Class} [original] The original class if it is a mock
6
+ */
7
+
8
+ /** @type {Map<string|Class, InstanceContext>} */
9
+ const singletons = new Map()
10
+ /** @type {Map<string|Class, InstanceContext>} */
11
+ const factories = new Map()
12
+
13
+ /**
14
+ * Register a class as a singleton. If a name is provided, it will be used as the key in the singleton map.
15
+ * Singleton instances only ever have one instance created via the @Inject decorator.
16
+ *
17
+ * @param {string} [name] The name of the singleton. If not provided, the class will be used as the key.
18
+ * @return {(function(*, *): void)|*}
19
+ * @example @Singleton() class MySingleton {}
20
+ * @example @Singleton('customName') class MySingleton {}
21
+ * @throws {Error} If the injection target is not a class
22
+ * @throws {Error} If a singleton with the same name is already defined
23
+ * @throws {Error} If a factory with the same name is already defined
24
+ */
25
+ export function Singleton(name) {
26
+ return function (clazz, context) {
27
+ if (context.kind !== "class") {
28
+ throw new Error('Invalid injection target')
29
+ }
30
+ if (singletons.has(name ?? clazz)) {
31
+ throw new Error('Singleton already defined')
32
+ }
33
+ if (factories.has(name ?? clazz)) {
34
+ throw new Error('Factory with the same name already defined')
35
+ }
36
+ singletons.set(name ?? clazz, { clazz })
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Register a class as a factory. If a name is provided, it will be used as the key in the factory map.
42
+ * Factory instances are created via the @Inject decorator. Each call to the factory will create a new instance.
43
+ *
44
+ * @param {string} [name] The name of the factory. If not provided, the class will be used as the key.
45
+ * @return {(function(*, *): void)|*}
46
+ * @example @Factory() class MyFactory {}
47
+ * @example @Factory('customName') class MyFactory {}
48
+ * @throws {Error} If the injection target is not a class
49
+ * @throws {Error} If a factory with the same name is already defined
50
+ * @throws {Error} If a singleton with the same name is already defined
51
+ */
52
+ export function Factory(name) {
53
+ return function (clazz, context) {
54
+ if (context.kind !== "class") {
55
+ throw new Error('Invalid injection target')
56
+ }
57
+ if (factories.has(name ?? clazz)) {
58
+ throw new Error('Factory already defined')
59
+ }
60
+ if (singletons.has(name ?? clazz)) {
61
+ throw new Error('Singleton with the same name already defined')
62
+ }
63
+ factories.set(name ?? clazz, { clazz })
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Inject a singleton or factory instance into a class field. You can also provide parameters to the constructor.
69
+ * If the instance is a singleton, it will only be created once with the first set of parameters it encounters.
70
+ *
71
+ * @param {string|Class} clazzOrName The singleton or factory class or name
72
+ * @param {*} params Parameters to pass to the constructor
73
+ * @return {(function(*): void)|*}
74
+ * @example @Inject(MySingleton) mySingleton
75
+ * @example @Inject("myCustomName") myFactory
76
+ * @throws {Error} If the injection target is not a field
77
+ * @throws {Error} If the injected field is assigned a value
78
+ */
79
+ export function Inject(clazzOrName, ...params) {
80
+ return function(initialValue, context) {
81
+ if (context.kind === "field") {
82
+ return function(initialValue) {
83
+ if (initialValue) {
84
+ throw new Error('Cannot assign value to injected field')
85
+ }
86
+ if (singletons.has(clazzOrName)) {
87
+ const instanceContext = singletons.get(clazzOrName)
88
+ if (!instanceContext.instance) {
89
+ singletons.set(clazzOrName, {clazz: clazzOrName, instance: new instanceContext.clazz(...params), original: instanceContext.original})
90
+ }
91
+ return singletons.get(clazzOrName).instance
92
+ } else if (factories.has(clazzOrName)) {
93
+ const factoryClass = factories.get(clazzOrName).clazz
94
+ return new factoryClass(...params)
95
+ } else {
96
+ throw new Error('Cannot find injection source with the provided name')
97
+ }
98
+ }
99
+ } else {
100
+ throw new Error('Invalid injection target')
101
+ }
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Mark a class as a mock. This will replace the class with a mock instance when injected.
107
+ * @param {string|Class} mockedClazzOrName The singleton or factory class or name to be mocked
108
+ * @return {(function(*, *): void)|*}
109
+ * @example @Mock(MySingleton) class MyMock {}
110
+ * @example @Mock("myCustomName") class MyMock {}
111
+ * @throws {Error} If the injection target is not a class
112
+ * @throws {Error} If the injection source is not found
113
+ */
114
+ export function Mock(mockedClazzOrName) {
115
+ return function(clazz, context) {
116
+ if (context.kind !== "class") {
117
+ throw new Error('Invalid injection target')
118
+ }
119
+ if (singletons.has(mockedClazzOrName)) {
120
+ const instanceContext = singletons.get(mockedClazzOrName)
121
+ instanceContext.original = instanceContext.clazz
122
+ instanceContext.clazz = clazz
123
+ } else if (factories.has(mockedClazzOrName)) {
124
+ const instanceContext = factories.get(mockedClazzOrName)
125
+ instanceContext.original = instanceContext.clazz
126
+ instanceContext.clazz = clazz
127
+ } else {
128
+ throw new Error('Cannot find injection source with the provided name')
129
+ }
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Reset all mocks to their original classes.
135
+ */
136
+ export function resetMocks() {
137
+ for (const instanceContext of singletons.values()) {
138
+ reset(instanceContext)
139
+ }
140
+ for (const instanceContext of factories.values()) {
141
+ reset(instanceContext)
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Reset a specific mock to its original class.
147
+ * @param {string|Class} clazzOrName The singleton or factory class or name to reset
148
+ */
149
+ export function resetMock(clazzOrName) {
150
+ const instanceContext = singletons.get(clazzOrName) ?? factories.get(clazzOrName)
151
+ reset(instanceContext)
152
+ }
153
+
154
+ /**
155
+ * Internal function to reset an instance context to its original.
156
+ * @param {InstanceContext} instanceContext The instance context to reset
157
+ * @private
158
+ */
159
+ function reset(instanceContext) {
160
+ if (!instanceContext) {
161
+ throw new Error('Cannot find injection source with the provided name')
162
+ }
163
+ if (instanceContext.original) {
164
+ instanceContext.clazz = instanceContext.original
165
+ delete instanceContext.original
166
+ delete instanceContext.instance
167
+ }
168
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "decorator-dependency-injection",
3
+ "version": "1.0.0",
4
+ "description": "A simple library for dependency injection using decorators",
5
+ "author": "Ravi Gairola <mallox@pyxzl.net>",
6
+ "license": "Apache-2.0",
7
+ "keywords": [
8
+ "dependency-injection",
9
+ "di",
10
+ "decorators",
11
+ "mocking"
12
+ ],
13
+ "main": "index.js",
14
+ "type": "module",
15
+ "scripts": {
16
+ "start": "babel-node index.js",
17
+ "test": "jest"
18
+ },
19
+ "jest": {
20
+ "transform": {
21
+ "^.+\\.js$": "babel-jest"
22
+ }
23
+ },
24
+ "devDependencies": {
25
+ "@babel/cli": "^7.26.4",
26
+ "@babel/core": "^7.26.9",
27
+ "@babel/plugin-proposal-decorators": "^7.25.9",
28
+ "@babel/polyfill": "^7.12.1",
29
+ "@babel/preset-env": "^7.26.9",
30
+ "@babel/register": "^7.25.9",
31
+ "@types/jest": "^29.5.14",
32
+ "jest": "^29.7.0"
33
+ }
34
+ }
@@ -0,0 +1,152 @@
1
+ import {Factory, Inject, Singleton} from '../index.js'
2
+
3
+ describe('Injection via fields', () => {
4
+ @Singleton()
5
+ class TestSingleton {
6
+ static calls = 0
7
+
8
+ constructor() {
9
+ TestSingleton.calls++
10
+ }
11
+ }
12
+
13
+ it('should inject singleton', () => {
14
+ class TestInjection {
15
+ @Inject(TestSingleton) testSingleton
16
+
17
+ constructor() {
18
+ expect(this.testSingleton).toBeInstanceOf(TestSingleton)
19
+ expect(TestSingleton.calls).toBe(1)
20
+ }
21
+ }
22
+
23
+ class TestInjection2 {
24
+ @Inject(TestSingleton) testSingleton
25
+
26
+ constructor() {
27
+ expect(this.testSingleton).toBeInstanceOf(TestSingleton)
28
+ expect(TestSingleton.calls).toBe(1)
29
+ }
30
+ }
31
+
32
+ new TestInjection()
33
+ new TestInjection2()
34
+ })
35
+
36
+ @Factory()
37
+ class TestFactory {
38
+ static calls = 0
39
+ params
40
+
41
+ @Inject(TestSingleton) testSingleton
42
+
43
+ constructor(...params) {
44
+ TestFactory.calls++
45
+ this.params = params
46
+ }
47
+ }
48
+
49
+ it('should inject factory', () => {
50
+ class TestInjectionFactory {
51
+ @Inject(TestFactory) testFactory
52
+
53
+ constructor() {
54
+ expect(this.testFactory).toBeInstanceOf(TestFactory)
55
+ expect(TestFactory.calls).toBe(1)
56
+ }
57
+ }
58
+
59
+ class TestInjectionFactory2 {
60
+ @Inject(TestFactory) testFactory
61
+
62
+ constructor() {
63
+ expect(this.testFactory).toBeInstanceOf(TestFactory)
64
+ expect(TestFactory.calls).toBe(2)
65
+ }
66
+ }
67
+
68
+ const result = new TestInjectionFactory()
69
+ new TestInjectionFactory2()
70
+ expect(result.testFactory.testSingleton).toBeInstanceOf(TestSingleton)
71
+ })
72
+
73
+ it('should inject factory with parameters', () => {
74
+ class TestInjectionFactoryParams {
75
+ @Inject(TestFactory, 'param1', 'param2') testFactory
76
+
77
+ constructor() {
78
+ expect(this.testFactory).toBeInstanceOf(TestFactory)
79
+ expect(this.testFactory.params).toEqual(['param1', 'param2'])
80
+ }
81
+ }
82
+
83
+ new TestInjectionFactoryParams()
84
+ })
85
+
86
+ @Singleton("named")
87
+ class NamedSingleton {
88
+ static calls = 0
89
+
90
+ constructor() {
91
+ NamedSingleton.calls++
92
+ }
93
+ }
94
+
95
+ it('should inject named singleton', () => {
96
+ class TestInjectionNamedSingleton {
97
+ @Inject("named") namedSingleton
98
+
99
+ constructor() {
100
+ expect(this.namedSingleton).toBeInstanceOf(NamedSingleton)
101
+ expect(NamedSingleton.calls).toBe(1)
102
+ }
103
+ }
104
+
105
+ class TestInjectionNamedSingleton2 {
106
+ @Inject("named") namedSingleton
107
+
108
+ constructor() {
109
+ expect(this.namedSingleton).toBeInstanceOf(NamedSingleton)
110
+ expect(NamedSingleton.calls).toBe(1)
111
+ }
112
+ }
113
+
114
+ new TestInjectionNamedSingleton()
115
+ new TestInjectionNamedSingleton2()
116
+ })
117
+
118
+ @Factory("named2")
119
+ class NamedFactory {
120
+ static calls = 0
121
+ params
122
+
123
+ constructor(...params) {
124
+ NamedFactory.calls++
125
+ this.params = params
126
+ }
127
+ }
128
+
129
+ it('should inject named factory', () => {
130
+ class TestInjectionNamedFactory {
131
+ @Inject("named2") namedFactory
132
+
133
+ constructor() {
134
+ expect(this.namedFactory).toBeInstanceOf(NamedFactory)
135
+ expect(NamedFactory.calls).toBe(1)
136
+ }
137
+ }
138
+
139
+ class TestInjectionNamedFactory2 {
140
+ @Inject("named2") namedFactory
141
+
142
+ constructor() {
143
+ expect(this.namedFactory).toBeInstanceOf(NamedFactory)
144
+ expect(NamedFactory.calls).toBe(2)
145
+ }
146
+ }
147
+
148
+ const result = new TestInjectionNamedFactory()
149
+ new TestInjectionNamedFactory2()
150
+ expect(result.namedFactory.params).toEqual([])
151
+ })
152
+ })
@@ -0,0 +1,57 @@
1
+ import {resetMocks, Inject, Mock, Singleton, Factory} from '../index.js'
2
+
3
+ describe('Mocking', () => {
4
+ @Singleton()
5
+ class ToBeMockedSingleton {
6
+ op() {
7
+ return 'original'
8
+ }
9
+ }
10
+
11
+ class TestInjection {
12
+ @Inject(ToBeMockedSingleton) toBeMockedSingleton
13
+ }
14
+
15
+ it('should inject a mock singleton', () => {
16
+ @Mock(ToBeMockedSingleton)
17
+ class MockedSingleton {
18
+ op() {
19
+ return 'mocked'
20
+ }
21
+ }
22
+
23
+ const result = new TestInjection()
24
+ expect(result.toBeMockedSingleton.op()).toBe('mocked')
25
+
26
+ resetMocks()
27
+ const result2 = new TestInjection()
28
+ expect(result2.toBeMockedSingleton.op()).toBe('original')
29
+ })
30
+
31
+ @Factory()
32
+ class ToBeMockedFactory {
33
+ op() {
34
+ return 'original'
35
+ }
36
+ }
37
+
38
+ class TestInjectionFactory {
39
+ @Inject(ToBeMockedFactory) toBeMockedFactory
40
+ }
41
+
42
+ it('should inject a mock factory', () => {
43
+ @Mock(ToBeMockedFactory)
44
+ class MockedFactory {
45
+ op() {
46
+ return 'mocked'
47
+ }
48
+ }
49
+
50
+ const result = new TestInjectionFactory()
51
+ expect(result.toBeMockedFactory.op()).toBe('mocked')
52
+
53
+ resetMocks()
54
+ const result2 = new TestInjectionFactory()
55
+ expect(result2.toBeMockedFactory.op()).toBe('original')
56
+ })
57
+ })