tunnckoCore / blankr

:heart: tasks, todos, ideas, streaks, WIP, etc
https://i.am.charlike.online
4 stars 1 forks source link

ask-once - ask all questions #46

Open tunnckoCore opened 8 years ago

tunnckoCore commented 8 years ago

just for backup, something like it will become question-store, but need more updates

'use strict'

var nal = require('now-and-later')
var set = require('set-value')
var get = require('get-value')

function askme (opts) {
  var res = {}
  opts = opts || {}
  opts.data = opts.data || {}
  opts.init = opts.init || false
  opts.force = opts.force || false

  return function (key, cb) {
    if (typeof key === 'function') {
      cb = key
      key = false
    }
    if (typeof cb !== 'function') {
      throw new TypeError('expect a done callback function')
    }

    if (!key) {
      nal.mapSeries(Object.keys(opts.questions.get()), iterator, function (err) {
        cb(err, res)
      })
      return
    }

    function iterator (k, next) {
      var value = opts.store.get(k)
      if (opts.init === true) {
        opts.store.del({force: true})
      }
      if (value) {
        var cache = opts.questions.cache
        if (typeof cache[k] === 'object') {
          Object.keys(cache[k]).map(function (kk) {
            return k + '.' + kk
          })
        }
        var val = get(cache, k, true)
        if (val) {
          val.default = value
          set(cache, k, val)
        }
      }
      if (!opts.questions.has(k, true)) {
        throw new Error('non existing question with key: ' + k)
      }
      if (opts.init || opts.force || !opts.store.has(k)) {
        opts.questions.ask(k, function (err, answer) {
          if (err) return next(err)
          set(res, k, get(answer, k))
          answer = get(res, k)
          opts.store.set(k, answer)
          next(null, answer)
        })
        return
      }
      set(res, k, value)
      next(null, get(res, k, true))
    }

    iterator(key, cb)
  }
}

example.js

'use strict'

var questions = require('question-cache')()
var store = require('data-store')('example', {cwd: process.cwd()})
var argv = require('minimist')(process.argv.slice(2), {
  alias: {force: 'f', init: 'i', a: 'ask'}
})

questions
  .set('name.first', 'Your first name?')
  .set('name.last', 'Your last name?')
  .set('foo', 'What you think for `foo`:')
  .set('bar', 'Give your `bar` here:')
  .set('baz', 'And what about baz?')
  .set('qux', 'Foo bar baz, now qux?')

var ask = askme({
  questions: questions,
  store: store,
  init: argv.init,
  force: argv.force
})

ask(argv.ask || false, function (err, answers) {
  console.log(err, answers)
})