From e2d9e9364099fe1f1992d4beaff1cbd56ad3df28 Mon Sep 17 00:00:00 2001 From: "Benjamin E. Coe" Date: Sun, 22 Nov 2020 18:04:49 -0500 Subject: [PATCH] docs: add example of using middleware with choices (#1813) Fixes #756 --- docs/api.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/api.md b/docs/api.md index 6b24ebc2e..1f88a0c07 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1087,6 +1087,39 @@ require('yargs/yargs')(process.argv.slice(2)) .parse() ``` +Example, Using middleware to apply a transformation on argv after `choices` have +been enforced ([see #756](https://github.com/yargs/yargs/issues/756)): + +```js +require('yargs') + .command('$0', 'accept username', () => {}, (argv) => { + // The middleware will have been applied before the default + // command is called: + console.info(argv); + }) + .choices('user', ['Goofy', 'Miky']) + .middleware(argv => { + console.info('gots here'); + const user = argv.user; + switch (user) { + case 'Goofy': + argv.user = { + firstName: 'Mark', + lastName: 'Pipe', + }; + break; + case 'Miky': + argv.user = { + firstName: 'Elon', + lastName: 'Stone', + }; + break; + } + return argv; + }) + .parse('--user Miky'); +``` + .nargs(key, count) -----------