hookFn.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var noop = require('./noop');
  2. var defaults = require('./defaults');
  3. var toArr = require('./toArr');
  4. var isArr = require('./isArr');
  5. var isErr = require('./isErr');
  6. exports = function(fn, options) {
  7. defaults(options, defOptions);
  8. return function() {
  9. var args = toArr(arguments);
  10. var newArgs = options.before.apply(this, args);
  11. if (isArr(newArgs)) {
  12. args = newArgs;
  13. }
  14. try {
  15. var result = fn.apply(this, args);
  16. var newResult = options.after.call(this, result);
  17. if (newResult) {
  18. result = newResult;
  19. }
  20. return result;
  21. } catch (e) {
  22. var newErr = options.error(e);
  23. if (newErr) {
  24. if (isErr(newErr)) {
  25. throw newErr;
  26. } else {
  27. return newErr;
  28. }
  29. }
  30. throw e;
  31. }
  32. };
  33. };
  34. var defOptions = {
  35. before: noop,
  36. after: noop,
  37. error: noop
  38. };
  39. module.exports = exports;