Advertisement
Guest User

Untitled

a guest
Apr 3rd, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. // Sometimes, you might want to supply *some* config, but
  2. // not necessarily *all*. Maybe your password is really
  3. // secret, so you don't want to risk saving it in a config
  4. // file. In which case, you'll want to ask the user to enter
  5. // it when your script runs.
  6.  
  7. // This interface provides a flexible approach, where
  8. // the user is prompted for a missing key when it's
  9. // requested - if a particular key isn't needed for a given
  10. // run, the user won't need to enter it. Of course, if the
  11. // particular key exists in the given config, the user isn't
  12. // asked.
  13.  
  14. const Task = require('data.task')
  15. const { ReaderT } = require('fantasy-readers')
  16. const { traverse } = require('ramda')
  17.  
  18. const { stdin: input, stdout: output } = process
  19.  
  20. // Ask the user a question on the command line.
  21. // question :: String -> Task e String
  22. const question = text => new Task((_, res) => {
  23. const rl = require('readline')
  24. .createInterface({ input: process.stdin
  25. , output: process.stdout
  26. , terminal: false })
  27.  
  28. return rl.question(
  29. `${ text }: `,
  30. data => { rl.close()
  31. res(data) })
  32. })
  33.  
  34. // type ReaderTask u e a = ReaderT u (Task e a)
  35. const ReaderTask = ReaderT(Task)
  36.  
  37. // Get a config key if it exists, or ask the user if not.
  38. // getConfig :: (String, String)
  39. // -> ReaderTask StrMap e String
  40. const getConfig = key =>
  41. ReaderTask.ask.chain(
  42. config => config[key] === undefined
  43. ? ReaderTask(_ => question(key))
  44. : ReaderTask.of(config[key]))
  45.  
  46. // Ask the user for any of the three keys that are missing,
  47. // then return all the values to be used.
  48. traverse(ReaderTask.of, getConfig,
  49. [ 'host', 'username', 'password' ])
  50.  
  51. // Do whatever fun thing with the values you need: connect
  52. // to a database, call an API, whatever.
  53. .map(([ host, user, pass ]) => ({ host, user, pass }))
  54.  
  55. // Pass in a potentially incomplete config array, whose
  56. // missing values will be populated by user input.
  57. .run({ 'host': 'localhost', 'username': 'tom' })
  58.  
  59. // None of the actions here can fail, so we'll just ignore
  60. // that and log the result!
  61. .fork(_ => undefined,
  62. x => console.log(x))
  63.  
  64. // $ node transformer.js
  65. // password: my-password
  66. // { host: 'localhost', user: 'tom', pass: 'my-password' }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement