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