( config: SelectFromListConfig<T>, listItems: (command: APICommand) => Promise<T[]>, createOptions?: CreateChooseFunctionOptions<T>, )
| 49 | customNotFoundMessage?: string |
| 50 | } |
| 51 | |
| 52 | export type ChooseFunction<T extends object> = ( |
| 53 | command: APICommand<SelectFromListFlags>, |
| 54 | itemIdOrIndexFromArg?: string, |
| 55 | options?: Partial<ChooseOptions<T>>) => Promise<string> |
| 56 | |
| 57 | export const createChooseFn = <T extends object>( |
| 58 | config: SelectFromListConfig<T>, |
| 59 | listItems: (command: APICommand) => Promise<T[]>, |
| 60 | createOptions?: CreateChooseFunctionOptions<T>, |
| 61 | ): ChooseFunction<T> => |
| 62 | async ( |
| 63 | command: APICommand<SelectFromListFlags>, |
| 64 | itemIdOrIndexFromArg?: string, |
| 65 | options?: Partial<ChooseOptions<T>>, |
| 66 | ): Promise<string> => { |
| 67 | const opts = chooseOptionsWithDefaults(options) |
| 68 | |
| 69 | // Listing items usually makes an API call which we only want to happen once so we do it |
| 70 | // now and just use stub functions that return these items later as needed. |
| 71 | let filteredItems: T[] | undefined = undefined |
| 72 | const listItemsWrapper = async (): Promise<T[]> => { |
| 73 | if (!filteredItems) { |
| 74 | const items = await (opts.listItems ?? listItems)(command) |
| 75 | filteredItems = opts.listFilter ? items.filter(opts.listFilter) : items |
| 76 | } |
| 77 | return filteredItems |
| 78 | } |
| 79 | |
| 80 | const preselectedId = opts.allowIndex |
| 81 | ? await stringTranslateToId(config, itemIdOrIndexFromArg, listItemsWrapper) |
| 82 | : itemIdOrIndexFromArg |
| 83 | |
| 84 | const selectOptions: SelectOptions<T> = { |
| 85 | preselectedId, |
| 86 | autoChoose: opts.autoChoose, |
| 87 | listItems: listItemsWrapper, |
| 88 | promptMessage: opts.promptMessage, |
| 89 | customNotFoundMessage: createOptions?.customNotFoundMessage, |
| 90 | notATTYMessage: opts.notATTYMessage, |
| 91 | } |
| 92 | |
| 93 | if (opts.useConfigDefault) { |
| 94 | const defaultValue = createOptions?.defaultValue |
| 95 | if (!defaultValue) { |
| 96 | throw Error('invalid state, the choose<Thing> function was called with "useConfigDefault"' + |
| 97 | ' but no default configured') |
| 98 | } |
| 99 | selectOptions.defaultValue = { |
| 100 | ...defaultValue, |
| 101 | getItem: (id: string): Promise<T> => defaultValue.getItem(command, id), |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | return selectFromList( |
| 106 | command, |
no test coverage detected