如何使用查询器设置答案的默认值?



我正在尝试创建一个小型构建脚本,如果在默认路径中找不到mysql标头,它将要求用户提供mysql标头的位置。现在我正在使用inquirer提示用户输入工作正常,但是我遇到了以下问题:

'use strict'
const inquirer = require('inquirer')
const fs = require('fs')
const MYSQL_INCLUDE_DIR = '/usr/include/mysql'
let questions = [
{
type: 'input',
name: 'MYSQL_INCLUDE_DIR',
message: 'Enter path to mysql headers',
default: MYSQL_INCLUDE_DIR,
when: (answers) => {
return !fs.existsSync(MYSQL_INCLUDE_DIR)
},
validate: (path) => {
return fs.existsSync(path)
}
}
]
inquirer.prompt(questions)
.then((answers) => {
// Problem is that answers.MYSQL_INCLUDE_DIR might be undefined at this point.
})

如果找到 mysql 标头的默认路径,则不会显示问题,因此不会设置答案。如何在不实际向用户显示问题的情况下为问题设置默认值?

解决上述问题也可以做到这一点,而不是使用全局变量:

let questions = [
{
type: 'input',
name: 'MYSQL_INCLUDE_DIR',
message: 'Enter path to mysql headers',
default: MYSQL_INCLUDE_DIR,
when: (answers) => {
return !fs.existsSync(answers.MYSQL_INCLUDE_DIR)
},
validate: (path) => {
return fs.existsSync(path)
}
}
]

怎么样:

inquirer.prompt(questions)
.then((answers) => {
const mysqlIncludeDir = answers && answers.MYSQL_INCLUDE_DIR ? answers.MYSQL_INCLUDE_DIR : MYSQL_INCLUDE_DIR;
})

或者更简洁地说:

inquirer.prompt(questions)
.then((answers) => {
const theAnswers = {
MYSQL_INCLUDE_DIR,
...answers
};
// theAnswers should be the answers you want
const mysqlIncludeDir = theAnswers.MYSQL_INCLUDE_DIR;
// mysqlIncludeDir should now be same as first solution above
})

或者更一般地在 lodash 的帮助下,像这样:

const myPrompt = (questions) => inquirer.prompt(questions)
.then((answers) => {
return {
...(_.omitBy(_.mapValues(_.keyBy(questions, 'name'), 'default'), q => !q)),
...answers
};
})
myPrompt(questions)
.then((answers) => {
// should be the answers you want
})

最后一个解决方案应该导致任何带有default的问题,以及一个可以隐藏其默认值的when,将其默认值强行包含在答案中。

最新更新