shimMethod.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. /*
  3. * cls-bluebird
  4. * Function to shim an object method to retain CLS context
  5. */
  6. // Modules
  7. var shimmer = require('shimmer');
  8. // Exports
  9. /**
  10. * Patch method to run callbacks in current CLS context.
  11. *
  12. * @param {Object} obj - Object on which to find method
  13. * @param {string} methodName - method name
  14. * @param {Array} args - Array of indexes of arguments which are callbacks
  15. * (negative numbers count from end e.g. -1 is last argument, -2 is penultimate)
  16. * @param {Object} ns - CLS namespace to bind callbacks to
  17. * @returns {undefined}
  18. */
  19. module.exports = function(obj, methodName, args, ns) {
  20. // Skip non-existent methods
  21. if (!obj[methodName]) return;
  22. // Patch method
  23. shimmer.wrap(obj, methodName, function(original) {
  24. return function() {
  25. for (var i = 0; i < args.length; i++) {
  26. var argIndex = args[i];
  27. if (argIndex < 0) argIndex += arguments.length;
  28. var callback = arguments[argIndex];
  29. if (typeof callback === 'function') arguments[argIndex] = ns.bind(callback);
  30. }
  31. return original.apply(this, arguments);
  32. };
  33. });
  34. };