New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Advanced prompt documentation improvement #35

Closed
jaykoontz opened this Issue Mar 13, 2018 · 3 comments

Comments

Projects
None yet
2 participants
@jaykoontz

jaykoontz commented Mar 13, 2018

Fantastic feature. I ran into a few roadblocks that I eventually overcame myself, so here's a more advanced example in case you find it useful. It covers:

  • ensuring all questions are asked before next prompt is executed
  • ensuring answers from both prompts are returned (was getting an error for missing template variables if I didn't do this explicitly)
  • parsing the first set of answers to create the next set of prompt questions
  • accessing dynamically-created variable names in the templates
module.exports = {
  prompt: ({ inquirer }) => {
    // defining questions in arrays ensures all questions are asked before next prompt is executed
    const questions = [{
      type: 'input',
      name: 'name',
      message: 'Name of form? (ex: AddContactForm)',
    },
    {
      type: 'confirm',
      name: 'shouldValidateForm',
      message: 'Do you need to validate the form?',
    },
    {
      type: 'input',
      name: 'formFieldNames',
      message: 'Field names? (separate by comma: "field1, field2,field3")',
    }]

    return inquirer
      .prompt(questions)
      .then(answers => {
        const { formFieldNames } = answers
        const questions = []

        // these values can be retrieved in the template with: eval(field + '.validation')
        formFieldNames.split(',').forEach((field) => {
          questions.push({
            type: 'input',
            name: field + '.validation',
            message: `Input the validation for ${field} (ex: isBlank(${field}) && '${field} is required')`,
          })
        })

        // both set of answers must be returned as a merged object, else the previous set of answers won't be available to the templates
        return inquirer.prompt(questions).then(nextAnswers => Object.assign({}, answers, nextAnswers))
      })
  },
}
@jondot

This comment has been minimized.

Owner

jondot commented Mar 14, 2018

Thanks! would you like me to include this example in the docs?

@jaykoontz

This comment has been minimized.

jaykoontz commented Mar 14, 2018

It covered a few pitfalls I faced when using the current example, but it is a bit long. Feel free to add it if you think it fits in the docs.

@jondot

This comment has been minimized.

Owner

jondot commented Mar 15, 2018

Done! added link to this issue and credit 🥇

@jondot jondot closed this Mar 15, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment