middleware.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.applyMiddleware = exports.commandMiddlewareFactory = exports.globalMiddlewareFactory = void 0;
  4. const argsert_1 = require("./argsert");
  5. const is_promise_1 = require("./is-promise");
  6. function globalMiddlewareFactory(globalMiddleware, context) {
  7. return function (callback, applyBeforeValidation = false) {
  8. argsert_1.argsert('<array|function> [boolean]', [callback, applyBeforeValidation], arguments.length);
  9. if (Array.isArray(callback)) {
  10. for (let i = 0; i < callback.length; i++) {
  11. if (typeof callback[i] !== 'function') {
  12. throw Error('middleware must be a function');
  13. }
  14. callback[i].applyBeforeValidation = applyBeforeValidation;
  15. }
  16. Array.prototype.push.apply(globalMiddleware, callback);
  17. }
  18. else if (typeof callback === 'function') {
  19. callback.applyBeforeValidation = applyBeforeValidation;
  20. globalMiddleware.push(callback);
  21. }
  22. return context;
  23. };
  24. }
  25. exports.globalMiddlewareFactory = globalMiddlewareFactory;
  26. function commandMiddlewareFactory(commandMiddleware) {
  27. if (!commandMiddleware)
  28. return [];
  29. return commandMiddleware.map(middleware => {
  30. middleware.applyBeforeValidation = false;
  31. return middleware;
  32. });
  33. }
  34. exports.commandMiddlewareFactory = commandMiddlewareFactory;
  35. function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
  36. const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true');
  37. return middlewares
  38. .reduce((acc, middleware) => {
  39. if (middleware.applyBeforeValidation !== beforeValidation) {
  40. return acc;
  41. }
  42. if (is_promise_1.isPromise(acc)) {
  43. return acc
  44. .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)]))
  45. .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
  46. }
  47. else {
  48. const result = middleware(acc, yargs);
  49. if (beforeValidation && is_promise_1.isPromise(result))
  50. throw beforeValidationError;
  51. return is_promise_1.isPromise(result)
  52. ? result.then(middlewareObj => Object.assign(acc, middlewareObj))
  53. : Object.assign(acc, result);
  54. }
  55. }, argv);
  56. }
  57. exports.applyMiddleware = applyMiddleware;