add.js 989 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. module.exports = addHook
  2. function addHook (state, kind, name, hook) {
  3. var orig = hook
  4. if (!state.registry[name]) {
  5. state.registry[name] = []
  6. }
  7. if (kind === 'before') {
  8. hook = function (method, options) {
  9. return Promise.resolve()
  10. .then(orig.bind(null, options))
  11. .then(method.bind(null, options))
  12. }
  13. }
  14. if (kind === 'after') {
  15. hook = function (method, options) {
  16. var result
  17. return Promise.resolve()
  18. .then(method.bind(null, options))
  19. .then(function (result_) {
  20. result = result_
  21. return orig(result, options)
  22. })
  23. .then(function () {
  24. return result
  25. })
  26. }
  27. }
  28. if (kind === 'error') {
  29. hook = function (method, options) {
  30. return Promise.resolve()
  31. .then(method.bind(null, options))
  32. .catch(function (error) {
  33. return orig(error, options)
  34. })
  35. }
  36. }
  37. state.registry[name].push({
  38. hook: hook,
  39. orig: orig
  40. })
  41. }