index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. module['exports'] = function bindHooks (Resource) {
  2. var arrObj = Object.getOwnPropertyNames(Resource.prototype);
  3. for ( var funcKey in arrObj ) {
  4. var og = Resource.prototype[arrObj[funcKey]];
  5. var localMethod = arrObj[funcKey];
  6. (function(og, localMethod){
  7. Resource.prototype[localMethod] = function _wrap () {
  8. var args = Array.prototype.slice.call(arguments);
  9. // todo: beforeAll hooks
  10. var self = this;
  11. beforeHooks(Resource.prototype[localMethod], args[0], function (err){
  12. var _cb = args[1];
  13. if (err) {
  14. return _cb(err);
  15. }
  16. og.call(self, args[0], function (err, d) {
  17. if (err) {
  18. return _cb(err);
  19. }
  20. afterHooks(Resource.prototype[localMethod], d, args[1]);
  21. })
  22. })
  23. }
  24. })(og, localMethod);
  25. Resource.prototype[localMethod].before = [];
  26. Resource.prototype[localMethod].after = [];
  27. }
  28. Resource.prototype.methods = {};
  29. Resource.prototype.before = function (localMethod, cb) {
  30. Resource.prototype[localMethod].before.unshift(cb);
  31. };
  32. Resource.prototype.after = function (localMethod, cb) {
  33. Resource.prototype[localMethod].after.push(cb);
  34. };
  35. return Resource;
  36. };
  37. function beforeHooks(fn, data, cb) {
  38. var hooks;
  39. var self = this;
  40. if (Array.isArray(fn.before) && fn.before.length > 0) {
  41. hooks = fn.before.slice();
  42. function iter() {
  43. var hook = hooks.pop();
  44. hook.call(self, data, function (err, r) {
  45. if (err) {
  46. return cb(err);
  47. }
  48. data = r;
  49. if (hooks.length > 0) {
  50. iter();
  51. }
  52. else {
  53. cb(null, data[0]);
  54. }
  55. });
  56. }
  57. iter();
  58. }
  59. else {
  60. return cb(null);
  61. }
  62. }
  63. function afterHooks(fn, data, cb) {
  64. cb = cb || function noop(){};
  65. var hooks;
  66. if (Array.isArray(fn.after) && fn.after.length > 0) {
  67. hooks = fn.after.slice();
  68. function iter() {
  69. var hook = hooks.shift();
  70. hook(data, function (err, d) {
  71. if (err) {
  72. return cb(err);
  73. }
  74. data = d;
  75. if (hooks.length > 0) {
  76. iter();
  77. }
  78. else {
  79. return cb(null, data);
  80. }
  81. });
  82. }
  83. iter();
  84. }
  85. else {
  86. cb(null, data);
  87. }
  88. }