Wednesday, February 26, 2014

Monkey patching Alfresco Repo JS webscript

While Alfresco Share is now has many methods of overloading, overriding, changing, adding, removing functionality. Alfresco Repository have few, and a common pattern for larger solution is to replace existing files fully overriding functionality. While this works it is hard to maintain.

1) Replace file by overriding, hard to maintain, 'cannot' be undone
2) Override URL, by making your own Webscript and specifying the same URL, this is better, but require files, and it does not work for *.lib.js files
 - for *.lib.js (imported files), you can override all the webscripts that use that lib-file, and in the overload import your own, thus no file is overridden ... but for some lib-files this means too much work for the gain

3) Change Share/Frontend code to use a different Repo-webscript (your own), then provide you own webscript. This can in many cases be done with share-configuration.


Future will probably improve this:
http://blogs.alfresco.com/wp/developer/2012/05/23/webscript-extensibility-on-the-alfresco-repository/

With approach 2 & 3 you will still have the original JS code in the Alfresco webapp, and this fact can be used to monkey-path the file, minimizing the amount of code to-be-written, increase reuse and maintainability.

Example, standard Repo webscript pattern:

A.get.js

<#import ../B.lib.js >

function C() { ... };

function main() { ... };

main();


Monkey- patch file:

D.get.js

<#import /full-path-to-A/A.lib.js >

function C() { .... monkey-patch-with-your-code... };


Now D.get.js will have the same functionality as A.get.js, but with your change ...


BUT the resulting file will have two C-functions! Yes, but javascript only runs the last declared ... so it works.

In the Javascrip debugger:



D.get.js - @runtime


<#import ../B.lib.js >

function C() { ... };

function main() { ... };

main();

function C() { .... monkey-patch-with-your-code... };


See this discussion: http://stackoverflow.com/questions/15810249/which-and-how-javascript-function-will-be-called-if-we-have-2-function-declarati