3 // hoisted due to circular dependency on command.
6 commandMiddlewareFactory,
7 globalMiddlewareFactory
9 const isPromise = require('./is-promise')
10 const argsert = require('./argsert')
12 function globalMiddlewareFactory (globalMiddleware, context) {
13 return function (callback, applyBeforeValidation = false) {
14 argsert('<array|function> [boolean]', [callback, applyBeforeValidation], arguments.length)
15 if (Array.isArray(callback)) {
16 for (let i = 0; i < callback.length; i++) {
17 if (typeof callback[i] !== 'function') {
18 throw Error('middleware must be a function')
20 callback[i].applyBeforeValidation = applyBeforeValidation
22 Array.prototype.push.apply(globalMiddleware, callback)
23 } else if (typeof callback === 'function') {
24 callback.applyBeforeValidation = applyBeforeValidation
25 globalMiddleware.push(callback)
31 function commandMiddlewareFactory (commandMiddleware) {
32 if (!commandMiddleware) return []
33 return commandMiddleware.map(middleware => {
34 middleware.applyBeforeValidation = false
39 function applyMiddleware (argv, yargs, middlewares, beforeValidation) {
40 const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true')
42 .reduce((accumulation, middleware) => {
43 if (middleware.applyBeforeValidation !== beforeValidation &&
44 !isPromise(accumulation)) {
48 if (isPromise(accumulation)) {
51 Promise.all([initialObj, middleware(initialObj, yargs)])
53 .then(([initialObj, middlewareObj]) =>
54 Object.assign(initialObj, middlewareObj)
57 const result = middleware(argv, yargs)
58 if (beforeValidation && isPromise(result)) throw beforeValidationError
60 return isPromise(result)
61 ? result.then(middlewareObj => Object.assign(accumulation, middlewareObj))
62 : Object.assign(accumulation, result)