Skip to content

Commit 8acabf9

Browse files
feat(action-chain): warn about constructor instantiation
1 parent 0239372 commit 8acabf9

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

packages/node_modules/action-chain/src/index.test.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ const context = {
6565
return 'baz'
6666
},
6767
},
68+
Constr: TestProvider,
6869
},
6970
test: new TestProvider(),
7071
}
@@ -185,6 +186,27 @@ describe('EFFECTS', () => {
185186
})
186187
fn()
187188
})
189+
test('should track execution of constructor instantiation', () => {
190+
expect.assertions(3)
191+
const fn = action().test(({ foo }) => {
192+
const instance = new foo.Constr()
193+
expect(instance.foo()).toBe('bar')
194+
expect(instance).toBeInstanceOf(TestProvider)
195+
})
196+
197+
actionChain.once('effect', (task) => {
198+
expect(task).toEqual({
199+
operatorId: 0,
200+
actionId: 0,
201+
executionId: 0,
202+
method: 'Constr',
203+
args: [],
204+
name: 'foo',
205+
result: '[Constr]',
206+
})
207+
})
208+
fn()
209+
})
188210
})
189211

190212
describe('ACTION CHAIN', () => {

packages/node_modules/action-chain/src/utils.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@ function isObject(value) {
66
return typeof value === 'object' && !Array.isArray(value) && value !== null
77
}
88

9+
let hasWarnedConstructor = false
10+
911
function createProxyGetHandler(
1012
path: string,
1113
cb: (effect: EffectResult) => void
1214
): ProxyHandler<any>['get'] {
1315
return (target, prop) => {
1416
if (typeof target[prop] === 'function') {
15-
return function(...args) {
17+
const func = function(...args) {
1618
const result = target[prop].apply(this, args)
1719
if (result instanceof Promise) {
1820
result.then((promisedResult) => {
@@ -35,6 +37,27 @@ function createProxyGetHandler(
3537
}
3638
return result
3739
}
40+
41+
return new Proxy(func, {
42+
construct(_, args) {
43+
// eslint-disable-next-line
44+
cb({
45+
name: path,
46+
method: prop,
47+
args,
48+
result: `[${prop.toString()}]`,
49+
})
50+
51+
if (!hasWarnedConstructor) {
52+
console.warn(
53+
`EFFECTS - It is highly recommended to create a custom effect, exposing a method that deals with the instantiation of "${path}.${prop.toString()}". It improves readability and debugability of your app`
54+
)
55+
hasWarnedConstructor = true
56+
}
57+
58+
return new target[prop](...args)
59+
},
60+
})
3861
}
3962
if (isObject(target[prop])) {
4063
return new Proxy(target[prop], {

0 commit comments

Comments
 (0)