Skip to content

Commit

Permalink
Merge pull request #31 from salesforcecli/mdonnalley/timed-prompt
Browse files Browse the repository at this point in the history
feat: add timedPrompt method
  • Loading branch information
mdonnalley authored Mar 8, 2022
2 parents 6466bc9 + 7d3d023 commit 7dc372a
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 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,33 @@ 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 @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 7dc372a

Please sign in to comment.