MCPcopy Create free account
hub / github.com/SmartThingsCommunity/smartthings-cli / createChooseFn

Function createChooseFn

src/lib/command/util/util-util.ts:51–103  ·  view source on GitHub ↗
(
	config: SelectFromListConfig<T>,
	listItems: (command: APICommand) => Promise<T[]>,
	createOptions?: CreateChooseFunctionOptions<T>,
)

Source from the content-addressed store, hash-verified

49 customNotFoundMessage?: string
50}
51
52export type ChooseFunction<T extends object> = (
53 command: APICommand<SelectFromListFlags>,
54 itemIdOrIndexFromArg?: string,
55 options?: Partial<ChooseOptions<T>>) => Promise<string>
56
57export 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,

Callers 15

chooseInviteFnFunction · 0.85
chooseDeviceProfileFnFunction · 0.85
chooseSchemaAppFnFunction · 0.85
chooseDriverFnFunction · 0.85
chooseInstalledAppFnFunction · 0.85
chooseSceneFnFunction · 0.85
chooseOrganizationFnFunction · 0.85
chooseLocationFnFunction · 0.85
chooseDevicePreferenceFnFunction · 0.85
chooseSchemaInvitationFnFunction · 0.85
chooseAppFnFunction · 0.85

Calls 3

stringTranslateToIdFunction · 0.85
selectFromListFunction · 0.85

Tested by

no test coverage detected