Ei kuvausta
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.js 2.1KB

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