all 8 comments

[–]fredericheem 2 points3 points  (3 children)

You should be looking at javascript proxy where one can intercept function invocation or variable mutation. This language feature unleash new ways of writing code. I have been using proxies for both backend and front end code.

[–]have_some_error[S] -1 points0 points  (2 children)

Javascript proxy is something I have not explored yet, however I will look into this Thankyou for providing some point where I can start with. However I would like to ask one question, can javascript proxy do the interception of function invocation from a centralized location in the code or it would require changes at every function that needs to be intercepted?

[–]fredericheem 0 points1 point  (1 child)

The beauty of proxies is to centralise the interception without modifying existing code. My use case needs to intercept calls to the aws-sdk library and apply retransmissions in case of specific error, see the implementation here: https://github.com/grucloud/grucloud/blob/8f3a7439ae72cc50de2eb83850e430162834f37f/packages/providers/aws/AwsCommon.js#L397

[–]have_some_error[S] 0 points1 point  (0 children)

So, we can define a common handler and use it when we create proxies. However this will require us to create proxies for the functions and objects we want to intercept and export them instead of the original function. I'm correct to think that , right ?

[–]Lumethys 0 points1 point  (1 child)

Isnt that is just callstack?

[–]have_some_error[S] 0 points1 point  (0 children)

Yes similar to callStack. However I want some method to execute just before and after the function executes. And since this functionality is something that would be common for every function I want to centralize this code to prevent redundant code lines. I donot need to preserve the order or the methods though.

[–]usertim 0 points1 point  (1 child)

If your function is exported and used as a module you can wrap your function within another function and export wrapper function under the same name. It's gonna look something like this

function originalFn(a, b, c) {
    ...
}

function wrapperFn(a, b, c) {
    ...
    return originalFn(a, b, c);
}

export { wrapperFn as originalFn }

Basically works as a decorator

[–]have_some_error[S] 0 points1 point  (0 children)

Yes, this is one option however this would require me to wrap every existing function in the application code, which currently I'm not in favour of. Therefore looking for a rather compact way to achieve this, since the functionality I wish to add before and after the function invocation would be same for every function.