@eljs/utils
Version:
Collection of nodejs utility.
82 lines (78 loc) • 2.03 kB
JavaScript
import { isNull } from "../type";
import prompts from 'prompts';
/**
* 确认问询
* @param message 闻讯信息
* @param preferNo 是否默认 false
* @param onCancel 取消回调函数
*/
export function confirm(message, preferNo, onCancel) {
onCancel = onCancel || function () {
return process.exit(1);
};
return prompts({
type: 'confirm',
message: message,
name: 'confirm',
initial: !preferNo
}, {
onCancel: onCancel
}).then(function (answers) {
return answers.confirm;
});
}
/**
* 选择问询
* @param message 问询信息
* @param choices 问询选项
* @param initial 初始数据
*/
export function select(message, choices, initial) {
var questions = [{
name: 'name',
message: message,
type: 'select',
choices: choices,
initial: initial
}];
return prompts(questions).then(function (answers) {
return answers.name;
});
}
/**
* 问询
* @param questions 问题列表
* @param initials 初始数据
*/
export function prompt(questions, initials) {
questions = questions.map(function (question) {
var copied = Object.assign({}, question);
var name = copied.name || '';
copied.type = copied.type || isNull(copied.type) ? copied.type : 'text';
if (initials !== null && initials !== void 0 && initials[name]) {
copied.initial = initials[name];
}
return copied;
});
return prompts(questions);
}
/**
* 循环问询
* @param questions 问题列表
* @param initials 初始数据
*/
export function loopPrompt(questions, initials) {
return prompt(questions, initials).then(function (answers) {
console.log();
console.log('The information you entered is as follows:');
console.log(JSON.stringify(answers, null, 2));
console.log();
return confirm('If the information is correct, press Y to confirm; if you need to re-enter, press N').then(function (isOK) {
if (isOK) {
return answers;
} else {
return loopPrompt(questions, answers);
}
});
});
}