UNPKG

1.42 kBJavaScriptView Raw
1/**
2 * Ask for configuration.
3 * @function askconfig
4 * @param {object} props - Values to ask.
5 * @param {object} [options] - Optional settings.
6 * @param {string} [options.msg] - Message to print before interaction.
7 * @returns {Promise}
8 */
9
10'use strict'
11
12const argx = require('argx')
13const objnest = require('objnest')
14const Question = require('./question')
15const questionInterface = require('./question_interface')
16
17/** @lends askconfig */
18async function askconfig (props, options = {}) {
19 const args = argx(arguments)
20 if (args.pop('function')) {
21 throw new Error('Callback is no longer supported. Use promise interface instead.')
22 }
23 props = args.shift()
24 options = args.pop('object') || {}
25
26 const {msg} = options
27 if (msg) {
28 [].concat(msg).forEach((msg) => {
29 console.log(msg)
30 })
31 }
32
33 const questions = Object.keys(props).map((key) => {
34 return Question.new({
35 key, default: props[key]
36 })
37 })
38
39 const qi = questionInterface()
40 const result = {}
41 let i = 0
42 for (const question of questions) {
43 const answer = await new Promise((resolve, reject) =>
44 qi.question(question.query(), (answer) => resolve(answer))
45 )
46 const key = question.key || i
47 i++
48 result[key] = String(answer || question.default).trim()
49 }
50 return new Promise((resolve) => {
51 qi.on('close', () => resolve(objnest.expand(result)))
52 qi.close()
53 })
54}
55
56module.exports = askconfig