Skip to content

Commit

Permalink
feat: add timedPrompt method
Browse files Browse the repository at this point in the history
  • Loading branch information
mdonnalley committed Mar 7, 2022
1 parent 4b0764d commit ea9e98c
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/ux/prompter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import { prompt, QuestionCollection, Separator, ChoiceOptions, ChoiceBase } from 'inquirer';
import { Dictionary, Nullable, ensureString } from '@salesforce/ts-types';
import { CliUx } from '@oclif/core';

export class Prompter {
/**
Expand All @@ -16,6 +17,35 @@ export class Prompter {
const answers = await prompt<T>(questions, initialAnswers);
return answers;
}

/**
* Prompt user for information with a timeout (in milliseconds). See https://www.npmjs.com/package/inquirer for more.
*/
public async timedPrompt<T = Prompter.Answers>(
questions: Prompter.Questions<T>,
ms = 10000,
initialAnswers?: Partial<T>
): Promise<T> {
let id: NodeJS.Timeout;
const thePrompt = prompt(questions, initialAnswers);
const timeout = new Promise((_, reject) => {
id = setTimeout(() => {
// eslint-disable-next-line no-console
// console.log(thePrompt.ui['activePrompt']);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
thePrompt.ui['activePrompt'].done();
CliUx.ux.log();
reject(new Error(`Timed out after ${ms} ms.`));
}, ms).unref();
});

return Promise.race([timeout, thePrompt]).then((result) => {
clearTimeout(id);
return result as T;
});
}
}

export namespace Prompter {
Expand Down

0 comments on commit ea9e98c

Please sign in to comment.