Skip to content

Commit

Permalink
feat(command): add command finish hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Petr Grishin committed Nov 7, 2019
1 parent c10c38c commit b449cd1
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 6 deletions.
14 changes: 14 additions & 0 deletions docs/advanced.md
Expand Up @@ -447,6 +447,20 @@ yargs.parserConfiguration({
See the [yargs-parser](https://github.com/yargs/yargs-parser#configuration) module
for detailed documentation of this feature.

## Command finish hook
### Example
```
yargs
.comand('cmd', ..., async () => {
await this.model.find()
return Promise.resolve('result value')
})
.onFinishCommand(async (resultValue) => {
await this.db.disconnect()
process.exit()
}).argv;
```

## Middleware

Sometimes you might want to transform arguments before they reach the command handler.
Expand Down
22 changes: 16 additions & 6 deletions lib/command.js
Expand Up @@ -242,13 +242,23 @@ module.exports = function command (yargs, usage, validation, globalMiddleware) {

if (isPromise(handlerResult)) {
yargs.getUsageInstance().cacheHelpMessage()
handlerResult.catch(error => {
try {
yargs.getUsageInstance().fail(null, error)
} catch (err) {
handlerResult
.then(value => {
if (yargs._onFinishCommand) {
return yargs._onFinishCommand(value)
}
})
.catch(error => {
try {
yargs.getUsageInstance().fail(null, error)
} catch (err) {
// fail's throwing would cause an unhandled rejection.
}
})
}
})
} else {
if (yargs._onFinishCommand) {
yargs._onFinishCommand(handlerResult)
}
}
}

Expand Down
32 changes: 32 additions & 0 deletions test/yargs.js
Expand Up @@ -2339,4 +2339,36 @@ describe('yargs dsl tests', () => {
})
})
})

describe('onFinishCommand', () => {
it('use with promise', (done) => {
const result = 'noop-result'
yargs(['noop']).command('noop', 'a noop command', noop, () => {
return Promise.resolve(result)
}).onFinishCommand(async (commandResult) => {
commandResult.should.eql(result)
})
.parse('noop', (err, argv) => {
if (err) {
return done(err)
}
return done()
})
})

it('use without promise', (done) => {
const result = 'noop-result'
yargs(['noop']).command('noop', 'a noop command', noop, () => {
return result
}).onFinishCommand(async (commandResult) => {
commandResult.should.eql(result)
})
.parse('noop', (err, argv) => {
if (err) {
return done(err)
}
return done()
})
})
})
})
6 changes: 6 additions & 0 deletions yargs.js
Expand Up @@ -483,6 +483,12 @@ function Yargs (processArgs, cwd, parentRequire) {
return self
}

self.onFinishCommand = function (f) {
argsert('<function>', [f], arguments.length)
self._onFinishCommand = f
return self
}

self.check = function (f, _global) {
argsert('<function> [boolean]', [f, _global], arguments.length)
validation.check(f, _global !== false)
Expand Down

0 comments on commit b449cd1

Please sign in to comment.