UNPKG

1.49 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 co = require('co')
13const argx = require('argx')
14const objnest = require('objnest')
15const Question = require('./question')
16const questionInterface = require('./question_interface')
17
18/** @lends askconfig */
19function askconfig (props, options = {}) {
20 let args = argx(arguments)
21 if (args.pop('function')) {
22 throw new Error('Callback is no longer supported. Use promise interface instead.')
23 }
24 props = args.shift()
25 options = args.pop('object') || {}
26
27 let { msg } = options
28 if (msg) {
29 [].concat(msg).forEach((msg) => {
30 console.log(msg)
31 })
32 }
33
34 let questions = Object.keys(props).map((key) => {
35 return Question.new({
36 key, default: props[ key ]
37 })
38 })
39
40 let qi = questionInterface()
41 let result = {}
42 let i = 0
43 return co(function * () {
44 for (let question of questions) {
45 let answer = yield new Promise((resolve, reject) =>
46 qi.question(question.query(), (answer) => resolve(answer))
47 )
48 let key = question.key || i
49 i++
50 result[ key ] = String(answer || question.default).trim()
51 }
52 return yield new Promise((resolve) => {
53 qi.on('close', () => resolve(objnest.expand(result)))
54 qi.close()
55 })
56 })
57}
58
59module.exports = askconfig