Skip to content

Commit

Permalink
fix: middleware added multiple times due to reference bug (#1282)
Browse files Browse the repository at this point in the history
  • Loading branch information
bcoe committed Jan 30, 2019
1 parent 61f1b25 commit 64af518
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
9 changes: 4 additions & 5 deletions lib/command.js
Expand Up @@ -17,12 +17,11 @@ module.exports = function command (yargs, usage, validation, globalMiddleware) {
let aliasMap = {}
let defaultCommand
globalMiddleware = globalMiddleware || []
self.addHandler = function addHandler (cmd, description, builder, handler, middlewares) {
self.addHandler = function addHandler (cmd, description, builder, handler, _middlewares) {
let aliases = []
const middlewares = (_middlewares || []).slice(0)
handler = handler || (() => {})
middlewares = middlewares || []
globalMiddleware.push(...middlewares)
middlewares = globalMiddleware

if (Array.isArray(cmd)) {
aliases = cmd.slice(1)
cmd = cmd[0]
Expand Down Expand Up @@ -232,7 +231,7 @@ module.exports = function command (yargs, usage, validation, globalMiddleware) {
if (commandHandler.handler && !yargs._hasOutput()) {
yargs._setHasOutput()

const middlewares = commandHandler.middlewares || []
const middlewares = globalMiddleware.slice(0).concat(commandHandler.middlewares || [])

innerArgv = applyMiddleware(innerArgv, middlewares)

Expand Down
21 changes: 21 additions & 0 deletions test/middleware.js
Expand Up @@ -140,4 +140,25 @@ describe('middleware', () => {
.parse()
})
})

// see: https://github.com/yargs/yargs/issues/1281
it("doesn't modify globalMiddleware array when executing middleware", () => {
let count = 0
yargs('bar')
.middleware((argv) => {
count++
})
.command('foo', 'foo command', () => {}, () => {}, [
() => {
count++
}
])
.command('bar', 'bar command', () => {}, () => {}, [
() => {
count++
}
])
.parse()
count.should.equal(2)
})
})

0 comments on commit 64af518

Please sign in to comment.