Last active
July 4, 2017 04:30
-
-
Save drewwyatt/b720f8a9f6ab26b7cac6be4f7314eb11 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Prompter, Validators } from './prompt'; | |
const main = async () => { | |
const inputs = await new Prompter() | |
.prompt('What is the auction id?', { validator: Validators.required }) | |
.then(p => p.prompt('Start Date?', { validator: Validators.isDate })) | |
.then(p => p.prompt('End Date?', { validator: Validators.isDate })) | |
.then(p => p.finish()); | |
console.log(inputs); | |
}; | |
main(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as readline from 'readline'; | |
import { optionalize } from '../optional'; | |
import { IQuestionConfig, Question } from './question'; | |
class Prompter { | |
async prompt(label: string, config: IQuestionConfig = {}): Promise<this> { | |
const question = new Question(label, config); | |
const [error, input] = await optionalize(question.ask(this._readLine)); | |
if (error) { | |
return this.prompt(label, config); | |
} | |
this._values.push(input as string); | |
return this; | |
} | |
finish(): string[] { | |
this._readLine.close(); | |
return this._values; | |
} | |
private _readLine: readline.ReadLine = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout, | |
}); | |
private _values: string[] = []; | |
} | |
export default Prompter; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ReadLine } from 'readline'; | |
interface IQuestionConfig { | |
default?: string; | |
validator?: (input: string) => boolean; | |
} | |
class Question { | |
label: string; | |
default: string; | |
validator: (i: string) => boolean; | |
constructor(label: string, config: IQuestionConfig = {}) { | |
this.label = label; | |
this.default = config.default || ''; | |
this.validator = config.validator || (_ => true); | |
} | |
ask(rl: ReadLine): Promise<string> { | |
return new Promise((resolve, reject) => { | |
rl.question(this.label, input => { | |
if (this.validator(input)) { | |
resolve(input || this.default); | |
} else { | |
reject('Input invalid.'); | |
} | |
}); | |
}); | |
} | |
} | |
export { IQuestionConfig, Question }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment