487ab3cc4df6f2d7c3b7e91e2b5e3d8037187cb4 — Martin Angers 5 months ago 6c40b42
extract league selection question
3 files changed, 33 insertions(+), 11 deletions(-)

M src/cmds/season_cmds/new.js
M src/constants.js
M src/questions.js
M src/cmds/season_cmds/new.js => src/cmds/season_cmds/new.js +2 -11
@@ 3,7 3,7 @@ import inquirer from 'inquirer'
 import { DB } from 'mymigrate'
 import { leaguesForNewSeason } from '../../leagues'
 import { nextSeasonForLeague } from '../../seasons'
-import { confirmQuestion } from '../../questions'
+import { confirmQuestion, listOrSelectLeagueQuestion } from '../../questions'
 import { Constants } from '../../constants'
 import exec from '../../handlers/season_cmds/new'
 


@@ 21,16 21,7 @@ export function builder (yargs) {
 function questions (conn, { league = '' }) {
   return () => {
     return inquirer.prompt ([
-      {
-        type: 'list',
-        name: 'leagueId',
-        message: 'Select league:',
-        choices () {
-          return leaguesForNewSeason (conn, league)
-            .then (ls => ls.map (l => { l.value = l.id; return l }))
-        },
-        pageSize: 10,
-      },
+      listOrSelectLeagueQuestion (conn, 'Select league:', leaguesForNewSeason, league),
       {
         type: 'number',
         name: 'year',

M src/constants.js => src/constants.js +1 -0
@@ 4,6 4,7 @@ const Constants = Object.freeze ({
   maxTeamNameLength: 100,
   minSeasonYear: 1900,
   maxSeasonYear: 2999,
+  defaultListPageSize: 10,
 })
 
 const PlayerName = Object.freeze ({

M src/questions.js => src/questions.js +30 -0
@@ 1,3 1,5 @@
+import { Constants } from './constants'
+
 export function confirmQuestion (msg) {
   return {
     type: 'confirm',


@@ 6,3 8,31 @@ export function confirmQuestion (msg) {
     default: true,
   }
 }
+
+export function listOrSelectLeagueQuestion (conn, msg, listFn, ...rest) {
+  return {
+    type: 'list',
+    name: 'leagueId',
+    message: msg,
+    pageSize: Constants.defaultListPageSize,
+
+    choices () {
+      return this.leagues.map (l => { l.value = l.id; return l })
+    },
+
+    async when (res) {
+      const leagues = await listFn (conn, ...rest)
+      this.leagues = leagues
+
+      if (this.leagues.length === 0) {
+        throw new Error ('no corresponding league')
+      }
+
+      if (this.leagues.length === 1) {
+        res.leagueId = this.leagues[0].id
+      }
+
+      return this.leagues.length > 1
+    },
+  }
+}